访问其他程序集中受保护的成员

本文关键字:受保护 成员 集中 程序集 其他 程序 访问 | 更新日期: 2023-09-27 17:57:28

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

在上面的简单代码中,

虽然我是从class2 派生的,但我无法访问程序集中2的字符串sample

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.

此定义是否仅适用于同一程序集,或者可以跨程序集访问受保护的成员?

访问其他程序集中受保护的成员

您可以从不同的程序集访问受保护的成员,但只能在子类中访问(对于受保护的访问来说是正常的(:

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

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

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

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

现在,上面的代码将运行。