开发者

Is there a technical reason why an automatic property must define both a get and set accessor

开发者 https://www.devze.com 2023-01-20 16:54 出处:网络
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.

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 prope开发者_开发问答rty 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/


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:

public object Property { get; private set; }

This provides you the ability to hide the set from outside, but still have a usable property.


public object Property { get; private set; } 

will work, and it will have the semantics you expect it to.


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.


From the C# spec:

Because the backing field is inaccessible, it can be read and written only through the property accessors, even within the containing type.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消