【问题标题】:Accessing protected members in a different assembly访问不同程序集中的受保护成员
【发布时间】:2014-05-21 06:49:36
【问题描述】:
using System.IO;
using System;
using Assembly2;

// DLL 1
namespace Assembly1
{
   class class1 : class2
   {
      static void Main()
      {
         Console.WriteLine(new class2().sample); //Cannot access. Protected means --> accessible to the derived classes right ? (But, note that this is a different assembly. Does not work because of that ?)
      }
   }
}

// DLL 2
namespace Assembly2
{
    public class class2
    {
      protected string sample = "Test";
    }
}

在上面的简单代码中,

我无法访问程序集 2 中的字符串 sample,尽管我派生自 class2

From MSDN: 

The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.

这个定义是只代表同一个程序集还是可以跨程序集访问受保护的成员?

【问题讨论】:

    标签: c# .net protected access-modifiers


    【解决方案1】:

    您可以从不同的程序集访问受保护的成员,但只能在子类中访问(与受保护的访问一样):

    // In DLL 1
    public class Class3 : class2
    {
        public void ShowSample()
        {
            Console.WriteLine(sample);
        }
    }
    

    请注意,即使这些类在同一个程序集中,您当前的代码也会失败。

    【讨论】:

    • 当我的问题得到 Jon Skeet 的回答时,它是 treat。谢谢乔恩。虽然我很傻。谢谢指点。
    • 还有一个问题。至于我的理解,如果是protected members can itself be accessible across assemblies,那为什么还需要protected internal呢?
    • 我尝试将成员 sample 设置为 protected internal 并且行为仍然相同?我不明白其中的意义:(
    • @nowhewhomustnotbenamed.: 不,protected internal 成员可以从同一程序集中的 any 类型访问。
    【解决方案2】:

    基类的受保护成员只有在通过派生类类型进行访问时才能在派生类中访问

    class class1:class2    
    {    
          static void Main()
          {
             Console.WriteLine(new class1().sample);
          }
     }
    

    现在上面的代码将运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-01
      • 2016-10-01
      • 2013-08-06
      • 2015-01-30
      • 1970-01-01
      • 2013-03-14
      • 2014-02-22
      相关资源
      最近更新 更多