Read only and write only automatic properties in Interface

天大地大妈咪最大 提交于 2019-12-12 15:11:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!