为什么 C# 不允许显式调用运算符或属性访问器?
C# 规范可能是这么说的,但即使我的搜索中没有显示任何内容,这也不是我正在寻找的答案。
我正在寻找一些场景,表明直接调用运算符方法(例如 op_Addition
)或属性访问器(例如 get_Length
)可能是一个坏主意。 C# 语言的设计者阻止我们这样做已经够糟糕的了。(请参阅编译器错误 CS0571。)
一种相当常见的情况是,拥有此功能会很有用,其中 Func
委托应该返回属性的值。您也不能将 get 访问器设置为委托的方法。有一个简单的解决方法(使用 () => someObject.SomeProperty
),但是,即使除了开销之外,它也不像 someObject.get_SomeProperty
那样清晰。
我看到的一个复杂问题是,当一个类型定义了到不同类型的多个转换时,这些方法将具有相同的签名和不同的返回类型,而 C# 也不允许这样做。但这是一个不同的问题。
The C# spec probably says so, but even though nothing showed up in my search, that's not the answer I'm looking for.
I'm looking for scenarios that show that calling operator methods (like op_Addition
) or property accessors (like get_Length
) directly might be a bad idea. Bad enough for the designers of the C# language to stop us from doing it. (See compiler error CS0571.)
One fairly common scenario where it would be useful to have this ability is where a Func<T>
delegate should return the value of a property. You can't make the get accessor the method of the delegate, either. There's a simple work-around (use () => someObject.SomeProperty
), but, even aside from the overhead, it's not as clear as someObject.get_SomeProperty
.
The one complication I see is that, when a type defines multiple conversions to different types, the methods would have the same signature with different return types, which C# doesn't allow either. But that's a different question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不知道为什么设计师(安德斯)选择不支持它,但这里有一些我想出的很好的理由。
如果初学者不知道属性 getter 的默认名称是 get_PropertyName(但如果它是标准编译器程序集则不必如此),这会让初学者感到困惑。
您可能会有一些永远不会使用该约定的 java-ophiles。
如果类设计者想要(并且这是有道理的),您可以有一个 Add 方法(如
DateTime.Add
)。这是一个更加友好的名称。Not sure why the designer (Anders) chose not to support it, but here are some good reasons I came up with.
It would be confusing to beginners who do not know that the default name for a property getter is get_PropertyName (but it doesn't have to be if it's a standard compiler assembly).
You would probably have some java-ophiles that would never use the convention.
If the class designer wanted to (and it makes sense), you can have an Add method (like
DateTime.Add
). That is a far more friendly name.