受保护的成员访问继承 [英] protected member access in inheritance
本文介绍了受保护的成员访问继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以通过派生类的对象初始化基类的受保护成员而不提供其set和get属性吗?
Can I initialize a protected member of the base class through the object of the derived class without providing its set and get properties?
推荐答案
是 - 并且没有。
您可以在派生类中访问它:
Yes - and no.
You can access it in the derived class:
public class Base
{
protected string myString;
}
public class Derived : Base
{
public Derived()
{
myString = "Hello World";
}
}
但您无法通过实例对象从外部访问它:
but you can't access it from outside either via the instance object:
private void MyMethod()
{
Derived d = new Derived();
d.myString = "goodbye"; //'MyNameSpace.Base.myString' is inaccessible due to its protection level
}
除非你将它封装在一个属性中并指定setter和getter:
Unless you encapsulate it in a property and specify the setter and getter:
private void MyMethod()
{
Derived d = new Derived();
d.MyString = "goodbye"; //All fine
}
...
public class Base
{
protected string myString;
}
public class Derived : Base
{
public string MyString { get { return myString; } set { myString = value; } }
public Derived()
{
myString = "Hello World";
}
}
这篇关于受保护的成员访问继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文