【问题标题】:in c#, is it possible to access the common protected fields of one child in another child class?在 C# 中,是否可以访问另一个子类中一个子类的公共受保护字段?
【发布时间】:2011-12-08 06:13:07
【问题描述】:

查看代码中的问题:

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 及其子项的范围内可访问。

【问题讨论】:

  • 当您尝试访问 myChild1.name 时是否出现任何错误?
  • 是的,我遇到了这个错误:错误 46 无法通过“child1”类型的限定符访问受保护的成员“commonParent.name”;限定符必须是“child2”类型(或派生自它)

标签: c# protected


【解决方案1】:

阅读以下 Eric Lippert 的博文,

尝试使用protected internal 会起作用的

【讨论】:

  • 不错的文章,虽然它没有给出任何答案。看来“受保护的内部”是我可以设置完成任务的最低能见度。
【解决方案2】:

你必须声明它至少受保护

【讨论】:

  • 我知道 - 他询问了内部或公众,所以我告诉他至少受保护.....
【解决方案3】:

我认为这是不好的设计,您应该将 Name 声明为 Private,并使用 Get、Set 访问器创建一个属性,您可以在其中选择 Get 或 Set 是否可以是 Public、Private 或 Protected,否则 Protected 将允许任何类访问字段或属性的相同命名空间。

【讨论】:

  • 是的,我知道这是规则。但在我的情况下,“名称”字段仅由 commonParent 类的所有孩子使用。我想从外部隐藏这个字段,但让它在 commonParent 及其子级范围内可访问。
【解决方案4】:

要回答您的问题,您可以使用反射访问它们。不过,这不是您想要依赖的东西。

【讨论】:

    【解决方案5】:

    我的方法是提供一个受保护的静态方法,该方法确实可以访问受保护的值,但仅对派生类可用,如下面的代码所示:

    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);
    
        }
    }
    

    这样做的好处是只为派生类提供对受保护数据的访问。

    【讨论】:

      猜你喜欢
      • 2016-01-16
      • 2012-07-22
      • 2013-05-27
      • 2013-07-10
      • 2012-05-09
      • 2011-12-25
      • 2013-03-25
      • 2014-04-04
      相关资源
      最近更新 更多