为什么属性 setter 和 getter 与 get_X 和 set_X 方法发生冲突?
在 .NET
中,属性应该是一等公民,但在 IL
代码中,属性 getter 和 setter 被实现为 get_
PropertyName< /em> 和 set_
PropertyName。
class Property
{
int Value { get { return 42; } }
int get_Value() { return 6 * 9; }
void set_Value(int i) { } // Error even though Value is a read only property
}
输出:
错误CS0082:类型“SO.Property”已保留具有相同参数类型的名为“get_Value”的成员
错误CS0082:类型“SO.Property”已保留具有相同参数类型的名为“set_Value”的成员
为什么<的设计者code>.NET 决定使用可能与用户代码冲突的名称? 他们可能使用了非法字符(因为 Java 使用 $
表示内部类内容)。
In .NET
properties are supposed to be first class citizens however in the IL
code property getters and setters are implemented as get_
PropertyName and set_
PropertyName.
class Property
{
int Value { get { return 42; } }
int get_Value() { return 6 * 9; }
void set_Value(int i) { } // Error even though Value is a read only property
}
Output:
error CS0082: Type 'SO.Property' already reserves a member called 'get_Value' with the same parameter types
error CS0082: Type 'SO.Property' already reserves a member called 'set_Value' with the same parameter types
Why did the designers of .NET
decide to use a name that may clash with user code? They could have used an illegal character (as Java uses $
for inner class stuff).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于没有属性概念的语言,例如 J#(这很可能影响了设计决策),仍然需要有一个简单的名称来调用它们。
For languages that don't have the concept of properties, such as J# (which may very well have influenced that design decision), it's still necessary to have a simple name to call them.
通用语言规范 (CLS) 要求使用 get_ 和 set_实现属性时,IL 中的方法(用特殊位修饰)。 这是必要的,以便不同的编译器(C#、托管 C++、VB.NET、J#、IronPython 等)创建可互操作的字节码。
因此,下划线不是广义上的“合法”字符。 它们不符合 CLS,因此不应在非私有接口中使用。
另请参阅 MSDN 上的这篇关于编写符合 CLS 的代码的文章。
The Common Language Specification (CLS) requires the use of get_ and set_ methods in the IL (decorated with special bits) when implementing Properties. This is necessary so that different compilers (C#, managed C++, VB.NET, J#, IronPython, etc.) create interoperable bytecodes.
Thus underscores are not "legal" characters in the broader sense. They are not CLS-compliant and therefore should not be used in non-private interfaces.
Also, see this article about writing CLS-compliant code on the MSDN.
因为它们可能需要从外部代码调用。
Because they may need to be called from external code.
好问题 - 大多数编译器生成的成员(匿名类型和方法)使用的名称保证不会与类中的任何成员冲突。 我认为这个特定的实例(以及事件方法的生成名称)是微软犯了一点错误的情况。
我能想到证明该决定合理的唯一原因是微软可能一直希望允许其他语言调用这些本身没有“属性”概念或语法的方法。
Good question - most of the compiler-generated members (anonymous types and methods) use names that are guaranteed to not clash with any members in your class. I think this particular instance (as well as the generated names for event methods) is a case where Microsoft made a little bit of a mistake.
The only reason I can think of that would justify the decision is that Microsoft may have been hoping to allow other languages to call these methods that do not themselves have a "property" concept or syntax.