C# getter/setter 幕后内部名称
我使用过显式 getters/setters,例如
private bool myField;
public bool MyField
{ get { return myField; }
set { myField = value; }
}
Now,使用 C# .net 4.0,您可以进行缩写,例如
public bool MyField
{ get; set; }
现在,如果我只想覆盖 SET 部分,我应该引用的内部引用是什么...在第一个示例中,我知道我明确指的是“myField”的私有属性,但是对于第二个版本,我指的是什么呢?编译器是否只是抛出隐含的“_”(例如 _MyField)作为元素的私有端?
Possible Duplicate:
Can I create an automatic property (no private member) with get and set code?
Access automatic property - c#
I've worked with explicit getters / setters such as
private bool myField;
public bool MyField
{ get { return myField; }
set { myField = value; }
}
Now, working with C# .net 4.0, you have the ability to abbreviate such as
public bool MyField
{ get; set; }
Now, if I want to override only the SET portion, what is the INTERNAL reference I should be referencing... in the first sample, I know I am explicitly referring to the private of "myField", but with the second version, what am I referencing? Does the compiler just throw an implied "_" such as _MyField as the private side of the element?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里,一个类继承了一个具有属性的类,并且仅覆盖了 setter。或者,您可以覆盖 getter 并将其保留为 return base.MyField 而不更改功能。
编辑:
提出的问题是,执行此操作时,子类中将不存在被遗漏的一半(我的示例中的 get ),从而使该属性只能读/写。事实并非如此,被遗漏的一半只是从其父级继承其功能。请参阅我的示例中添加的以下内容进行演示。
(这确实会打印“hi”,编译或运行时没有错误。)
Here a class inherits from a class with a property an overrides only the setter. Alternatively you could override the getter and just leave it as return base.MyField to not change the functionality.
Edit:
The issue was raised that when doing this the half that was left out (the get in my example) wouldn't exist in the child class, making the property read/write only. That is not the case, the half that is left out simply inherits its functionality from its parent. See the following addition to my example to demonstrate.
(This will indeed print "hi", no errors compile or runtime.)
在这种情况下,编译器所做的一切都是实现细节,将来可能会更改,恕不另行通知!
因此,我强烈建议不要让您的代码依赖于这样的实现细节,而在这种情况下只使用第一个选项(覆盖两个访问器并具有字段来显式支持属性)...
whatever the compiler does in this case is an implementation detail which can change in the future without further notice!
Thus I strongly recommend to not make your code depend on such an implementation detail and just use the first option (override both accessors and have field to explicitely back the property) in this case...
您可以使用
MyField
以相同的方式访问该属性。但是,如果您不希望类外部的代码能够设置该属性,您可以使用:You would access the property in the same way, using
MyField
. However, if you did not want code outside the class to be able to set the property, you can use: