2016-01-18 28 views
1

下面的例子:如何使接口強制執行沒有setter?

interface ISomeInterface 
{ 
    string SomeProperty { get; } 
} 

我已經編譯執行:

public class SomeClass : ISomeInterface 
{ 
    public string SomeProperty 
    { 
     get 
     { 
      throw new NotImplementedException(); 
     } 
     set 
     { 
      throw new NotImplementedException(); 
     } 
    } 
} 

這是一個問題。我如何使界面成爲一個合同,不允許在其中實施?

注意:我不是在尋找一個解決方案如何避免設置在實現中,但在接口,將驗證它從任何新的實現,謝謝。

+3

有沒有辦法做到這一點。 – SLaks

+0

這就是我的想法,我希望是錯誤的 – RollRoll

+2

這是什麼要求/用戶案例? – rae1

回答

3

接口只指定必須實現的內容,但不限制其他方法或屬性也可以實現。

所以get是你唯一指定的東西。

由於您對該集合保持沉默,所以接口的任何實現者都可以自由添加或不添加集合。

總之,使用接口規範,你不能做你想做的事情。

2

如果你想確保設定不會被調用,然後你總是可以投的實例接口

如果你真的需要確保沒有設置,你可以使用一個抽象類,而不是一個接口

abstract class SomeInterface 
{ 
    virtual string SomeProperty { get; } 
} 
1

基於邁克的回答,你可以寫這樣的事情:

public interface ISomeInterface 
{ 
    string SomeProperty { get; } 
} 

public abstract class SomeInterfaceBase : ISomeInterface 
{ 
    public abstract string SomeProperty { get; } 
} 

所以,你可以定義這樣的類:

public class SomeClass : SomeInterfaceBase 
{ 
    public override string SomeProperty { get; } 
} 

如果試圖實現setter,它將不會編譯。

1

有一個setter不是一個問題。原因是因爲我們如何對待接口。

具體類是否有setter或不是無關緊要,因爲我們應該將對象視爲一個ISomeInterface。在這種情況下,它只有一個setter。

例如讓我們一個工廠方法:

class Program 
{ 
    interface ISomeInterface 
    { 
     string SomeProperty { get; } 
    } 

    static ISomeInterface CreateSomeClass() 
    { 
     return new SomeClass(); 
    } 

    class SomeClass : ISomeInterface 
    { 
     public string SomeProperty 
     { 
      get 
      { 
       throw new NotImplementedException(); 
      } 
      set 
      { 
       throw new NotImplementedException(); 
      } 
     } 
    } 

    static void Main(string[] args) 
    { 
     ISomeInterface someInterface = CreateSomeClass(); 
     someInterface.SomeProperty = "test"; //Wont compile 
    } 
} 

類的實現二傳手是沒有意義的,因爲我們只是在治療對象ISomeInterface感興趣。接口是附加的。換句話說,它們定義了需要定義什麼的合同,而不是什麼不應該定義的合同。

如果我是把它以任何其他方式,這將是這樣的:

((SomeClass) someInterface).SomeProperty = "test"; //Code smell 

,我會考慮代碼味道,因爲它假設someInterface是SomeClass的(處理接口,具體類)