2017-06-20 63 views
-3

如何限制類變量不繼承或更改派生類中的值?如何限制字段不要編輯派生類中的c#

EX-

Class A 
{ 
    public string name="ABC"; 
} 
Class B:A 
{ 
    //I don't want here name property of base class should be accessible 
    or can be changed 
} 
+2

讓你的公共領域向私人 –

+0

喜@BhubanShrestha,但不是真正的私有成員訪問在派生類 – user2147163

+0

[如何隱藏類中的繼承屬性而不修改繼承類(基類)]的可能重複?](https://stackoverflow.com/questions/1875401/how-to-hide-an-inherited -property-IN-A級,而無需修飾最繼承-C la) –

回答

3

你能與私人裝置使用的屬性如下:

class A 
{ 
    public string Name 
    { 
     get; 
     private set; 
    } 
} 

class B:A 
{ 
    public B() 
    { 
     this.Name = "Derived"; // This will not work. If you want to prevent the derived class from accessing the field, just mark the field as private instead of public. 
    } 
}