简体   繁体   中英

Accessing protected members in a different assembly

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

In the above simple code,

I cannot access the string sample in assembly 2 though I am deriving from 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. 

Does this definition stand only for the same assembly or can the protected members be accessed across assemblies ?

You can access the protected member from a different assembly, but only within a subclass (as normal for protected access):

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

Note that your current code would fail even if the classes were in the same assembly.

A protected member of a base class is accessible in a derived class only if the access occurs through the derived class type .

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

now above code will run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM