c#关键字 static

static 修饰符可用于声明 static 类。 在类、接口和结构中,可以将 static 修饰符添加到字段、方法、属性、运算符、事件和构造函数。 static 修饰符不能用于索引器或终结器

尽管类的实例包含该类的所有实例字段的单独副本,但每个 static 字段只有一个副本。

不可以使用 this 引用 static 方法或属性访问器。

类、接口和 static 类可以具有 static 构造函数。 在程序开始和实例化类之间的某个时刻调用 static 构造函数。

静态类

静态类的所有成员都必须为 static。

csharp 复制代码
//静态类
static class CompanyEmployee
{
    //静态类的所有成员都必须为 static
    public static void DoSomething() { /*...*/ }
    public static void DoSomethingElse() { /*...*/  }
}

常数或类型声明是隐式的 static 成员。 不能通过实例引用 static 成员。 然而,可以通过类型名称引用它。

csharp 复制代码
public class MyBaseC
{
    public struct MyStruct
    {
        public static int x = 100;
    }
}

若要引用 static 成员 x,除非可从相同范围访问该成员,否则请使用完全限定的名称 MyBaseC.MyStruct.x:

csharp 复制代码
Console.WriteLine(MyBaseC.MyStruct.x);

静态字段和方法

csharp 复制代码
public static int employeeCounter;

    public static int AddEmployee()
    {
        return ++employeeCounter;
    }

静态初始化

此示例演示了如何使用尚未声明的 static 字段来初始化另一个 static 字段。 在向 static 字段显式赋值之后才会定义结果。

csharp 复制代码
class Test
{
    static int x = y; //尚未声明的 static 字段y来初始化另一个 static 字段x
    static int y = 5;

    static void Main()
    {
        Console.WriteLine(Test.x);
        Console.WriteLine(Test.y);

        Test.x = 99;
        Console.WriteLine(Test.x);
    }
}
/*
Output:
    0
    5
    99
*/
相关推荐
Paul_09201 小时前
golang面经——map模块和sync.Map模块
开发语言
Univin1 小时前
C++(10.5)
开发语言·c++·算法
haogexiaole2 小时前
Java高并发常见架构、处理方式、api调优
java·开发语言·架构
张人玉2 小时前
C# 通讯关键类的API
开发语言·c#
froginwe112 小时前
R 数组:深入解析与高效使用
开发语言
tao3556672 小时前
【Python刷力扣hot100】283. Move Zeroes
开发语言·python·leetcode
progalchemist2 小时前
Quick SwiftObjective-C测试框架入门教程
开发语言·其他·objective-c·swift
z日火3 小时前
Java 泛型
java·开发语言
广药门徒3 小时前
Linux(含嵌入式设备如泰山派)VNC 完整配置指南:含开机自启动(适配 Ubuntu/Debian 系)
开发语言·php