简体   繁体   中英

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

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/

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; } 

会工作,它会有你期望的语义。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM