2017-06-20 62 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. 
    } 
}