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";
}
}
在上面的简单代码中,
虽然我来自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.
此定义是仅代表同一个程序集还是可以跨程序集访问受保护的成员?
答案 0 :(得分:3)
您可以从其他程序集访问受保护的成员,但只能在子类中访问(正常情况下受保护访问):
// In DLL 1
public class Class3 : class2
{
public void ShowSample()
{
Console.WriteLine(sample);
}
}
请注意,即使这些类在同一个程序集中,您当前的代码也会失败。
答案 1 :(得分:0)
只有通过派生类类型进行访问时,才能在派生类中访问基类的受保护成员。
class class1:class2
{
static void Main()
{
Console.WriteLine(new class1().sample);
}
}
现在上面的代码将运行。