C# 当用户调用未定义的属性/方法时,我是否可以返回特定的内容?
使用fluent模式编写对象,并希望任何未定义的属性(或方法)返回该对象(此) 例如:C# 当用户调用未定义的属性/方法时,我是否可以返回特定的内容?,c#,.net,C#,.net,使用fluent模式编写对象,并希望任何未定义的属性(或方法)返回该对象(此) 例如: public class Please { private float nDegrees; public Please Rotate(float nDegrees) { this.nDegrees = nDegrees; return this; } // code to make all other calls => this; } var foo = new Pl
public class Please {
private float nDegrees;
public Please Rotate(float nDegrees) {
this.nDegrees = nDegrees;
return this;
}
// code to make all other calls => this;
}
var foo = new Please().Rotate(n).Degrees; // Degrees should return the Instance of Please it was called on
var bar = new Please().Rotate(n).To.Do.The.Thing; // should also return the instance of please it was called on
你能澄清一下“调用未定义的方法”下的意思吗“这在某种程度上是可能的,但它会增加很多复杂性并放弃编译时安全性。为什么要这样做?@DzianisKarpuk,如示例所示。未在类
请中定义度,但会返回一些内容。在我的例子中,它只是返回它被调用的对象@约翰武只含合成糖。我怀疑这是我做不到的,但我想我会问。你希望ngrees
是什么类型的?你还没有申报;您的意思是让Rotate
返回请
而不是float
?对未定义属性或方法的任何调用都会导致编译失败。动态或反射可以做到这一点,但同样,您会丢失编译时验证。通常,与动态语言不同,当一个属性不存在时,它意味着永远不应该调用它。请澄清一下,在“调用一个未定义的方法”下你是什么意思“这在某种程度上是可能的,但它会增加很多复杂性并放弃编译时安全性。为什么要这样做?@DzianisKarpuk,如示例所示。未在类请中定义度,但会返回一些内容。在我的例子中,它只是返回它被调用的对象@约翰武只含合成糖。我怀疑这是我做不到的,但我想我会问。你希望ngrees
是什么类型的?你还没有申报;您的意思是让Rotate
返回请
而不是float
?对未定义属性或方法的任何调用都会导致编译失败。动态或反射可以做到这一点,但同样,您会丢失编译时验证。通常,与动态语言不同,当属性不存在时,它意味着永远不应该调用它。