C# .NET 中的受保护类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1017778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:38:33  来源:igfitidea点击:

Protected Classes in .NET

c#.netaccess-modifiers

提问by Aarsh Thakur

Can a class be protected in.NET?
Why is / isn't this possible?

可以在 .NET 中保护类吗?
为什么/这不可能?

采纳答案by ShuggyCoUk

Yes, you just cannot make them top level classes, they must be inner classes

是的,你不能让它们成为顶级类,它们必须是内部类

public class Outer
{
    protected class Foo
    {
    }
}

This is fine, it means that the only classes allowed to see Foo are sub classes of Outer

这很好,这意味着唯一允许看到 Foo 的类是 Outer 的子类

class X 
{
    // 'Outer.Foo' is inaccessible due to its protection level
    private void Flibble(Outer.Foo foo)
    {
    }
}

class X : Outer
{
    // fine
    private void Flibble(Outer.Foo foo)
    {
    }
}

Note that you cannot declare any outer class as private, protected (or protected internal) in c# since the access modifier for outer level classes defines their visibility in relation to other assemblies. Specifically visible within the assembly only (or to friends via InternalsVisibleTo) or outside the assembly.

请注意,您不能在 c# 中将任何外部类声明为私有、受保护(或受保护内部),因为外部类的访问修饰符定义了它们相对于其他程序集的可见性。仅在程序集内(或通过 InternalsVisibleTo 对朋友可见)或程序集外特别可见。

Thus whilst the public/internal identifiers are used here for consistency really the state in IL is simply 'Public' or 'NonPublic' (as the Reflection.Emit flags show)

因此,虽然这里使用公共/内部标识符来保持一致性,但 IL 中的状态实际上只是“公共”或“非公共”(如Reflection.Emit 标志所示

回答by Nader Shirazie

protectedvisibility is used to indicate 'visible to derived classes'. This makes sense on things inside a class, but normally has no meaning at the class level.

protected可见性用于指示“对派生类可见”。这对类内的事物有意义,但在类级别通常没有意义。

The only exception to this is an inner class, where protected visibility means that derived classes will have access to the inner class.

唯一的例外是内部类,其中受保护的可见性意味着派生类将可以访问内部类。

回答by Aarsh Thakur

Yes, we just cannot make them top level classes, they must be inner classes

是的,我们不能让它们成为顶级类,它们必须是内部类

回答by Vinay Chanumolu

A protected class could not be defined inside a namespace.It could only be declared as a nested class. It could be instantiated inside other nested classes and could be inherited by other nested classes and It can inherit from other nested classes.

不能在命名空间内定义受保护的类。它只能声明为嵌套类。它可以在其他嵌套类中实例化,可以被其他嵌套类继承,也可以从其他嵌套类继承。

A protected member of a parent class could be accessed by the nested classes as well as the classes that inherit from the parent class (Derived Class or Child Class).

嵌套类以及从父类继承的类(派生类或子类)可以访问父类的受保护成员。