尽管有各种解释,我仍然想要了解一些事情。 内部和受保护之间的唯一区别是在项目中使用它吗?
谢谢,
塔尔
答案 0 :(得分:3)
AFAIK没有受保护或内部项目。项目包含类和其他类型,并且是项目中可以具有不同访问修饰符的那些元素。
内部修饰符:只能在同一个程序集中引用/加入(相同的.exe或.dll)
受保护的修饰符:可以从继承自他的类中引用/接受,继承它的类可能位于另一个程序集中(例如,公共类中的受保护方法,只能从另一个继承的类中调用)从它,但该类可能在另一个程序集/项目中,因为该类被声明为公共)。
还有其他辅助功能修饰符,其中一个我刚才提到过:
公共修饰符:可以从同一个程序集或其他程序集中的类中引用/加入。
私有修饰符:可以从已声明的同一个类中引用/加入。
实施例
Assembly/Project1
public class ClassA {
private string variable1;
protected string variable2;
public string variable3;
internal string variable4;
public void MyFancyProcess()
{
Console.Write(variable1);
}
}
public class ClassB : ClassA {
public string variable5;
private void DoSomeStuff()
{
Console.Write(variable1); // This would raise an error, its is private and only could be called from ClassA *even if ClassB is child of ClassA*
Console.Write(variable2); // I can access variable2 because it is protected *AND ClassB is child of ClassA*
Console.Write(variable3); // This would work, public has no restrictions
Console.Write(variable4); // This would work, ClassB and ClassA share same assembly
}
}
internal class ClassC
{
ClassA myAClassInstance = new ClassA();
Console.Write(myAClassInstance.variable1); // This would raise an error, it is exclusive to ClassA and we are in ClassC
Console.Write(myAClassInstance.variable2); // This would raise an error, because ClassC does not inherit ClassA
Console.Write(myAClassInstance.variable3);
Console.Write(myAClassInstance.variable4); // This would work, ClassC and ClassA share same assembly
}
Assembly/ProjectB
public class ClassD : ClassA // Please note that if ClassA where not public it would raise an error
{
public void ExecuteMyLogic()
{
Console.Write(variable1); // This would raise an error, its is private and only could be called from ClassA
Console.Write(variable2); // I can access variable2 because it is protected *AND ClassD is child of ClassA despite being a different assembly*
Console.Write(variable3); // This would work, public has no restrictions
Console.Write(variable4); // This would raise an error, they are different assemblies
}
}