3 回答

TA貢獻1827條經(jīng)驗 獲得超8個贊
在接口中,您不能限制對屬性的訪問,因此我認(rèn)為您不能強制實現(xiàn)該接口的類來限制該訪問。
或者你可以使用一個抽象類,你可以在其中限制訪問,但一個不太仁慈的實現(xiàn)者仍然可以輕松地覆蓋抽象類的限制訪問屬性。
interface IMyClass
{
string MyProperty { get; } // this does nothing against implementing a setter!
}
abstract class MyAbstracClass : IMyClass
{
string MyProperty { get; protected set; } // otherwise we cannot set it from inheritors
}
class MyClass : MyAbstractClass
{
public new string MyProperty { get; set; } // nothing stops this!
public MyClass (string prop) => MyProperty = prop;
}
抽象類選項確實意味著開發(fā)人員不能“意外地”公開該屬性。即使您設(shè)法將其隱藏起來,任何真正想要訪問私有屬性的開發(fā)人員都可以簡單地使用反射。不過,這也不是偶然發(fā)生的,并且應(yīng)該始終在代碼審查時發(fā)出危險信號!

TA貢獻1712條經(jīng)驗 獲得超3個贊
public class Implementer : Enforcer
{
private readonly string _propy;
public string Propy
{
get => _propy;
set => throw new InvalidOperationException();
}
public Implementer(string propy) { _propy = propy; }
}
設(shè)置時拋出異常,或者您可以更改接口以僅在實現(xiàn)中獲取和執(zhí)行私有集

TA貢獻1826條經(jīng)驗 獲得超6個贊
public class Implementer : Enforcer
{
private string _propy;
public string Propy
{
get
{
return _propy;
}
set
{
// do nothing. so readonly.
}
}
public Implementer(string propy) { _propy = propy; }
}
- 3 回答
- 0 關(guān)注
- 121 瀏覽
添加回答
舉報