在 C# 中,static 是属于类型而非实例的关键字或修饰符。因此实例不需要访问静态成员。在 C# 中,静态可以是字段、方法、构造函数、类、属性、运算符和事件。
内存效率:现在我们不需要创建实例来访问静态成员,所以它节省了内存。而且,它属于类型,所以每次创建实例时不会获取内存。
声明为静态的字段称为静态字段。与每次创建对象时都会获取内存的实例字段不同,在内存中只创建了一个静态字段的副本。它被所有对象共享。
它用于引用所有对象的公共属性,例如在 Account 的情况下为 rateOfInterest,在 Employee 的情况下为 companyName 等。
让我们看一下 C# 中静态字段的简单示例。
using System; public class Account { public int accno; public String name; public static float rateOfInterest=8.8f; public Account(int accno, String name) { this.accno = accno; this.name = name; } public void display() { Console.WriteLine(accno + " " + name + " " + rateOfInterest); } } class TestAccount{ public static void Main(string[] args) { Account a1 = new Account(101, "Sonoo"); Account a2 = new Account(102, "Mahesh"); a1.display(); a2.display(); } }
输出:
101 Sonoo 8.8 102 Mahesh 8.8
如果更改静态字段的值,它将应用于所有对象。
using System; public class Account { public int accno; public String name; public static float rateOfInterest=8.8f; public Account(int accno, String name) { this.accno = accno; this.name = name; } public void display() { Console.WriteLine(accno + " " + name + " " + rateOfInterest); } } class TestAccount{ public static void Main(string[] args) { Account.rateOfInterest = 10.5f;//changing value Account a1 = new Account(101, "Sonoo"); Account a2 = new Account(102, "Mahesh"); a1.display(); a2.display(); } }
输出:
101 Sonoo 10.5 102 Mahesh 10.5
让我们看另一个在 C# 中统计对象的 static 关键字示例。
using System; public class Account { public int accno; public String name; public static int count=0; public Account(int accno, String name) { this.accno = accno; this.name = name; count++; } public void display() { Console.WriteLine(accno + " " + name); } } class TestAccount{ public static void Main(string[] args) { Account a1 = new Account(101, "Sonoo"); Account a2 = new Account(102, "Mahesh"); Account a3 = new Account(103, "Ajeet"); a1.display(); a2.display(); a3.display(); Console.WriteLine("Total Objects are: "+Account.count); } }
输出:
101 Sonoo 102 Mahesh 103 Ajeet 对象总数:3