2014-11-14 61 views
3

我想有一個只讀出的界面,讀取裏面執行/寫性能

interface IFoo 
{ 
    string Foo { get; } 
} 

與像的實現:

abstract class Bar : IFoo 
{ 
    string IFoo.Foo { get; private set; } 
} 

我想的屬性爲gettable通過接口,但只能在具體實現中寫入。最乾淨的方法是什麼?我是否需要「手動」實現getter和setter?

+3

'protected'是要走的路。 – Jay 2014-11-14 19:10:12

+0

你能澄清嗎? '字符串PartitionKey {get;保護組; }'產生一個錯誤「可訪問性修飾符不能在接口的訪問器上使用」 – bfops 2014-11-14 19:13:28

+3

您需要實現帶有支持字段的屬性 - 然後您將能夠從具體實現中訪問該字段(設置爲受保護時) 。我不認爲你可以通過自動屬性來實現。 – MarcinJuraszek 2014-11-14 19:14:24

回答

4
interface IFoo 
{ 
    string Foo { get; } 
} 


abstract class Bar : IFoo 
{ 
    public string Foo { get; protected set; } 
} 

幾乎是你有,但protected和班裏的屬性掉落IFoo.

我建議protected假設你只希望它可以從INSIDE派生類訪問。相反,如果你希望它是完全公開(可在類的外部設置過),只要用:

public string Foo { get; set; } 
+0

啊,完美,謝謝!我認爲'Bar'內的屬性必須是'IFoo.Foo',這給了我錯誤。 – bfops 2014-11-14 19:20:34

+0

但它給出錯誤「訪問者必須更加嚴格......」 – Ahmad 2014-11-14 19:30:01

+0

@Ahmad不,它不! http://tinypic.com/r/2aihi8m/8 – 2014-11-14 19:38:05

0

只需使用protected set,也拆除IFO的屬性之前,使之隱。

interface IFoo 
{ 
    string Foo { get; } 
} 
abstract class Bar : IFoo 
{ 
    public string Foo { get; protected set; } 
} 
+0

因爲這是一個明確的實現,所以你不能添加setter。 – juharr 2014-11-14 19:17:08

+0

對,也使用'protected'也有錯誤 – Ahmad 2014-11-14 19:19:34

+0

@juharr Huh?夥計們,那是不正確的!上面的代碼不會產生任何錯誤:http://i.imgur.com/sLcXpeh.png – 2014-11-14 20:05:04

2

爲什麼顯式的實現接口?這將編譯,沒有問題的作品:

interface IFoo { string Foo { get; } } 
abstract class Bar : IFoo { public string Foo { get; protected set; } } 

否則,你可能對類保護/私有財產,並明確實現接口,但委託吸氣到類的getter。

2

要麼使實現隱而不顯

abstract class Bar : IFoo 
{ 
    public string Foo { get; protected set; } 
} 

或者添加支持字段

abstract class Bar : IFoo 
{ 
    protected string _foo; 
    string IFoo.Foo { get { return _foo; } } 
}