首页 > C#教程 阅读:16816

C# static:静态成员

C# 中,我们可以使用 static 关键字声明属于类型本身而不是属于特定对象的静态成员,因此不需要使用对象来访问静态成员。在类、接口和结构体中可以使用 static 关键字修饰变量、函数、构造函数、类、属性、运算符和事件。

注意:索引器和析构函数不能是静态的。

若在定义某个成员时使用 static 关键字,则表示该类仅存在此成员的一个实例,也就是说当我们将一个类的成员声明为静态成员时,无论创建多少个该类的对象,静态成员只会被创建一次,这个静态成员会被所有对象共享。

1、静态属性

使用 static 定义的成员属性称为“静态属性”,静态属性可以直接通过 类名.属性名的形式直接访问,不需要事先创建类的实例。静态属性不仅可以使用成员函数来初始化,还可以直接在类外进行初始化。

下面通过一个示例来演示一下静态变量的使用:
using System;
namespace c.biancheng.net
{
 class Demo
 {
 static void Main(string[] args) 
 {
 Test.str = "C语言中文网";
 Console.WriteLine(Test.str);
 Test test1 = new Test();
 test1.getStr();
 
 Test test2 = new Test();
 test2.getStr();
 test2.setStr("http://c.biancheng.net/");
 test1.getStr();
 test2.getStr();
 }
 }
 public class Test
 {
 public static string str;
 public void setStr(string s){
 str = s;
 }
 public void getStr(){
 Console.WriteLine(str);
 }
 }
}
运行结果如下:

C语言中文网
C语言中文网
C语言中文网
http://c.biancheng.net/
http://c.biancheng.net/

2、静态函数

除了可以定义静态属性外,static 关键字还可以用来定义成员函数,使用 static 定义的成员函数称为“静态函数”,静态函数只能访问静态属性。

下面通过示例来演示静态函数的使用:
using System;
namespace c.biancheng.net
{
 class Demo
 {
 static void Main(string[] args) 
 {
 Test test1 = new Test();
 test1.setStr("C语言中文网");
 Test.getStr();
 Test test2 = new Test();
 test2.setStr("http://c.biancheng.net/");
 Test.getStr();
 }
 }
 public class Test
 {
 public static string str;
 public void setStr(string s){
 str = s;
 }
 public static void getStr(){
 Console.WriteLine(str);
 }
 }
}
运行结果如下:

C语言中文网
http://c.biancheng.net/

AltStyle によって変換されたページ (->オリジナル) /