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
*/
相关推荐
古城小栈几秒前
Go 1.25 发布:性能、工具与生态的全面进化
开发语言·后端·golang
@syh.14 分钟前
【C++】map和set
开发语言·c++
拾光Ծ24 分钟前
C++11实用的“新特性”:列表初始化+右值引用与偷懒艺术——移动语义
开发语言·c++
何憶树之長青28 分钟前
Kernel
开发语言·php
hardmenstudent28 分钟前
Python字典--第1关:元组使用:这份菜单能修改吗?
开发语言·python
John_Rey43 分钟前
Rust底层深度探究:自定义分配器(Allocators)——控制内存分配的精妙艺术
开发语言·后端·rust
逻极43 分钟前
VS Code之Java 开发完全指南:从环境搭建到实战优化
java·开发语言
月月玩代码1 小时前
SLF4J,简单门面Java日志框架
java·开发语言
moeyui7051 小时前
Python文件编码读取和处理整理知识点
开发语言·前端·python
·心猿意码·1 小时前
C# 垃圾回收机制深度解析
开发语言·c#