问题
I had read that auto implemented properties cannot be read only or write only. They can only be read-write.
However, while learning interfaces I came across foll. code, which creates a read only / write only and read-write type of automatic properties. Is that acceptable?
public interface IPointy
{
// A read-write property in an interface would look like:
// retType PropName { get; set; }
// while a write-only property in an interface would be:
// retType PropName { set; }
byte Points { get; }
}
回答1:
That is not auto-implemented. Interfaces do not contain implementation.
It's a declaration that the interface IPointy requires a property of type byte, named Points, with a public getter.
You can implement the interface in any way necessary as long as there is a public getter; whether by an auto-property:
public class Foo: IPointy
{
public byte Points {get; set;}
}
Note the setter can still be private:
public class Bar: IPointy
{
public byte Points {get; private set;}
}
Or, you can explicitly write a getter:
public class Baz: IPointy
{
private byte _points;
public byte Points
{
get { return _points; }
}
}
来源:https://stackoverflow.com/questions/30022654/read-only-and-write-only-automatic-properties-in-interface