I just wonder is there is a logical r开发者_JAVA百科eason why read-only and write-only automatic properties are not supported by c#.
(i.e. I mean properties with only a get or set, but not both. If you try to define an automatic property like this, you get a compiler error telling you that auto properties must have both get and set).
Is it just to stop people accidentally forgetting to add one?
Thanks
From the C# 3.0 spec:
When a property is specified as an automatically implemented property, a hidden backing field is automatically available for the property, and the accessors are implemented to read from and write to that backing field.
Because the backing field is inaccessible, it can be read and written only through the property accessors. This means that automatically implemented read-only or write-only properties do not make sense, and are disallowed. It is however possible to set the access level of each accessor differently. Thus, the effect of a read-only property with a private backing field can be mimicked like this:
public class ReadOnlyPoint {
public int X { get; private set; }
public int Y { get; private set; }
public ReadOnlyPoint(int x, int y) { X = x; Y = y; }
}
You can make a read-only property by making the setter private:
class A {
public int Foo { get; private set; }
}
What are you trying to get here when there never will be a set value?
MyPorperty { get; }
Even if you set the property, what is the benefit if you cannot get the value anyways?
MyProperty { set; }
If you want external code to only see set or get accessors, you can use the private keyword like this:
MyProperty { get; private set; }
or
MyProperty { private get; set; }
If you have only a getter, how could this auto-property return something usefull ?
The same logic apply for the setter.
:)
If your idea is inheritance then, you can flag it abstract and do what you want :
//this compiles successfully
public abstract Name { get; }
//this tooo
public abstract Age { set; }
Um, what would you do with such a property? There's no way to assign a value to an automatic property other than via the setter, and there's no way to read from one other than via the writer. So what use would it be to be able to read a value that can only ever be the default or to write a value that you'll never be able to get back?
精彩评论