2015-05-04 123 views
3

我讀過自動實現的屬性不能只讀或只寫。他們只能讀寫。在接口中只讀和只寫自動屬性

但是,雖然學習接口,我碰到foll。代碼,它創建一個只讀/只寫和讀寫類型的自動屬性。這可以接受嗎?

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

回答

9

這不是自動實現的。接口不包含實現。

這是一個聲明,表明該接口IPointy需要一個byte型,命名爲Points的財產,有一個公共的getter


只要有公共getter,您可以以任何必要的方式實現接口;無論是通過自動屬性:

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

注意的制定者仍然可以是私有的:

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

或者,您可以明確寫入一個getter:

public class Baz: IPointy 
{ 
    private byte _points; 

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