在c#中,是否有可能在另一个子类中访问一个子类的公共受保护字段?
本文关键字:子类 一个 字段 受保护 是否 有可能 另一个 访问 | 更新日期: 2023-09-27 18:11:32
见代码中的问题:
class commonParent {
protected string name;
}
class child1:commonParent{
// do some stuff
}
class child2:commonParent{
// do some stuff
protected void test(){
child1 myChild1 = new child1();
//is it possible to access myChild1.name in child2 without
//declaring the name public or internal?
// I want to do something like this:
string oldName = myChild1.name;
//but I got the error:
//Error 46 Cannot access protected member 'commonParent.name'
//via a qualifier of type 'child1'; the qualifier must be of
//type 'child2' (or derived from it)
}
}
字段"name"只被commonParent类的所有子类使用。我想隐藏这个字段从外部(类不是从commonParent派生),而让它在commonParent和它的子范围内访问。
阅读Eric Lippert的博客文章,
- 为什么不能从派生类访问受保护的成员?
尝试使用protected internal
,它将工作
你必须声明它至少是受保护的
我认为这是一个糟糕的设计,你应该声明Name为Private,并创建一个带有Get,Set访问器的属性,在那里你可以选择Get或Set是否可以是Public,Private或Protected,否则Protected将允许相同命名空间的任何类访问字段或属性。
回答您的问题,您可以使用反射访问它们。但这不是你想要依赖的东西。
我的方法是提供一个受保护的静态方法,该方法可以访问受保护的值,但只对派生类可用,如下面的代码所示:
class commonParent
{
protected string name;
protected static string GetName(commonParent other)
{
return other.name;
}
}
class child1 : commonParent
{
// do some stuff
}
class child2 : commonParent
{
protected void test()
{
child1 myChild1 = new child1();
string oldName = commonParent.GetName(myChild1);
}
}