是否存在技术原因导致自动属性必须同时定义 get 和 set 访问器
我知道自动属性必须定义 get 和 set 访问器方法,我也知道可以通过访问修饰符使这些访问器中的任何一个变得不可见。
是否存在编译器满意
public object Property { get; set; }
但不满意的
public object Property { get; }
技术原因我对此代码的理解(可能是错误的)是编译器生成一个对调用代码隐藏的支持字段,如下所示:
private object hiddenField; //hidden by compiler.
public object Property
{
get { return hiddenField; }
set { hiddenField = value;}
}
如果编译器可以生成它,那么是否有一个这是因为它不能根据属性声明中是否存在 setter 来省略 set 访问器函数。
我知道这可能是功能范围问题而不是技术限制,我也坦白承认我还没有查阅 C# 语言规范。
[更新2]
原谅我...我是个白痴:P,我现在明白了,谢谢大家容忍我的高年级时刻/
I know that automatic properties must define a get and set accessor method, I also know that it is possible for either of these accessors to be made invisible by means of an access modifier.
Is there a technical reason why the compiler is happy with
public object Property { get; set; }
but not
public object Property { get; }
My (possibly wrong) understanding of this code is that the compiler generates a backing field that is hidden from the calling code like so:
private object hiddenField; //hidden by compiler.
public object Property
{
get { return hiddenField; }
set { hiddenField = value;}
}
If the compiler can generate that, is there a reason that it can't omit the set accessor function based on the presence (or lack thereof) of a setter in the property declaration.
I understand that this may be an issue of feature scope rather than a technical limitation, I also freely admit that I have not yet consulted the C# language specification as yet.
[UPDATE 2]
Forgive me...I'm an idiot :P, I see now, thank you everyone for tollerating my senior moment/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果没有 set 访问器,就无法设置该值,因为您无法访问“hiddenField”。
同样,如果没有 get 访问器,就无法取回您设置的值。
既然真的变得没用了,那就不允许了。
但是,您可以对这两种方法具有不同的可访问性:
这使您能够从外部隐藏该集,但仍然具有可用的属性。
Without the set accessor, there is no way to set the value, since you don't have a way to access "hiddenField".
Similarly, without a get accessor, there would be no way to get back a value you set.
Since it really becomes useless, it's not allowed.
However, you can have different accessibility on the two methods:
This provides you the ability to hide the set from outside, but still have a usable property.
将会起作用,并且它将具有您期望的语义。
will work, and it will have the semantics you expect it to.
您如何使用以下属性?
公共对象属性 { get;理论上
,如果您可以编写类似的内容,它总是返回 null,因为它缺少 set 访问器。我认为除非您以某种方式设置隐藏字段以具有静态值以始终返回它,否则它是没有用的。
How could you use a property such the following?
public object Property { get; }
Theoritically if you could write something like that it always returns null as it lacks to the set accessor. I think it is useless unless you set the hidden field in some way to have a static value to always return it.
来自 C# 规范:
省略其中一个访问器意味着该属性要么是只读的,要么是只写的,即使在类/结构的构造函数中也是如此。不是很有用。
From the C# spec:
Leaving one of the accessors out would mean that the property would either be read-only or write-only, even within the constructor of the class/struct. Not very useful.