受保护的VS内部有什么不同?

问题描述 投票:-5回答:1

尽管有各种解释,我仍然想要了解一些事情。内部和受保护之间的唯一区别是在项目中使用它?

谢谢,

c# .net
1个回答
3
投票

AFAIK不存在受保护或内部项目。项目包含类和其他类型,并且是项目内可以具有不同访问修饰符的那些元素。

内部修饰符:只能在同一个程序集中引用/接受(相同的.exe或.dll)

受保护的修饰符:可以从继承自他的类中引用/接受,继承它的类可能位于另一个程序集中(例如,公共类中的受保护方法,只能从继承自它的另一个类中调用,但是这个类可能在另一个程序集/项目中,因为该类被声明为public。

还有其他可访问性修饰符,其中一个我刚刚提到:

公共修饰符:可以从同一程序集或其他程序集中的类引用/加入。

私有修饰符:可以从已声明的同一个类中引用/加入。

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
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.