大学期间我一直在使用public,想知道public, private和protected之间的区别吗?

还有,相对于什么都没有,静态有什么作用呢?


当前回答

当前访问修饰符的另一种可视化方法(c# 7.2)。希望这个模式能帮助你更容易地记住它 (请按此图片浏览。)

外内

如果你很难记住两个词的访问修饰符,记住由外而内。

Private protected:外部私有(相同程序集)内部受保护(相同程序集) 保内:保外(同一组件)保内(同一组件)

其他回答

这些访问修饰符指定成员可见的位置。你应该读读这个。以IainMH给出的链接为起点。

静态成员是每个类一个,而不是每个实例一个。

图形概述(简要总结)

实际上,情况要比这复杂一些。 现在(从c# 7.2开始),也有private protected,派生类是否在同一个程序集中也很重要。

因此,需要扩展概述:

请参阅有关此主题的c# -dotnet-docs。

因为静态类是密封的,所以它们不能被继承(除非是从Object继承),所以关键字protected在静态类上是无效的。

对于默认情况,如果你在前面不放访问修饰符,请参见这里: c#类和成员(字段,方法等)的默认可见性?

Non-nested

enum                              public
non-nested classes / structs      internal
interfaces                        internal
delegates in namespace            internal
class/struct member(s)            private
delegates nested in class/struct  private

嵌套:

nested enum      public
nested interface public
nested class     private
nested struct    private

此外,还有seal -关键字,它使类不可继承。 同样,在VB中。NET,关键字有时是不同的,所以这里有一个小抄:

我创建了另一种类型的可视化。也许这是更好的理解方式

https://github.com/TropinAlexey/C-sharp-Access-Modifiers

访问修饰符

从learn.microsoft.com:

public The type or member can be accessed by any other code in the same assembly or another assembly that references it. private The type or member can only be accessed by code in the same class or struct. protected The type or member can only be accessed by code in the same class or struct, or in a derived class. private protected (added in C# 7.2) The type or member can only be accessed by code in the same class or struct, or in a derived class from the same assembly, but not from another assembly. internal The type or member can be accessed by any code in the same assembly, but not from another assembly. protected internal The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.

如果没有设置访问修饰符,则使用默认访问修饰符。所以总有某种形式的访问修饰符,即使它没有设置。

静态修饰符

类上的静态修饰符意味着该类不能被实例化,并且它的所有成员都是静态的。静态成员只有一个版本,不管创建了多少个其封闭类型的实例。

静态类基本上与非静态类相同,但有一个区别:静态类不能被外部实例化。换句话说,不能使用new关键字创建类类型的变量。因为没有实例变量,所以可以使用类名本身访问静态类的成员。

然而,存在一种静态构造函数。任何类都可以有其中一个,包括静态类。它们不能被直接调用,也不能有参数(除了类本身的任何类型参数)。在创建第一个实例或引用任何静态成员之前,会自动调用静态构造函数来初始化类。看起来是这样的:

static class Foo()
{
    static Foo()
    {
        Bar = "fubar";
    }
    
    public static string Bar { get; set; }
}

静态类通常被用作服务,你可以这样使用它们:

MyStaticClass.ServiceMethod(...);

当前访问修饰符的另一种可视化方法(c# 7.2)。希望这个模式能帮助你更容易地记住它 (请按此图片浏览。)

外内

如果你很难记住两个词的访问修饰符,记住由外而内。

Private protected:外部私有(相同程序集)内部受保护(相同程序集) 保内:保外(同一组件)保内(同一组件)