只读和只写接口中的自动属性

Read only and write only automatic properties in Interface

我读到自动实现的属性不能只读或只写。它们只能是可读写的。

然而,在学习界面时,我遇到了很多问题。代码,它创建一个只读/只写和读写类型的自动属性。这是可以接受的吗?

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

这不是自动实现的。接口不包含实现。

声明接口 IPointy 需要 a 属性 类型 byte,名称为 Points,带有 public getter.


只要有public getter,您可以以任何必要的方式实现接口;是否通过自动 属性:

public class Foo: IPointy
{
    public byte Points {get; set;}
}

请注意 setter 仍然可以是私有的:

public class Bar: IPointy
{
    public byte Points {get; private set;}
}

或者,您可以明确地写一个 getter:

public class Baz: IPointy
{
    private byte _points;

    public byte Points
    {
        get { return _points; }
    }
}