C#中的静态构造函数

我想要使​​用像下面这样的静态构造函数:

public static DataManager() { LastInfoID = 1; } 

并得到这个错误:

静态构造函数不允许访问修饰符

我想知道我的问题是什么。

静态构造函数没有访问修饰符:它只是:

 static DataManager() // note no "public" { LastInfoID = 1; } 

这是因为它永远不会显式调用(除了可能通过reflection) – 但是由运行时调用; 访问级别是没有意义的。

问题是LastInfoID字段或属性没有在您的类中声明为静态 ,您只能从静态构造函数访问静态成员。 从声明中删除public关键字:

 static DataManager() { LastInfoID = 1; } 

删除public 。 静态构造函数的语法是:

 class MyClass { static MyClass() { // Static constructor } } 

给这里的任何人一个更明确的答案,没有一个例子,想想为什么你将不得不从外部访问静态构造函数? 静态类是在应用程序执行时在内存中创build的,这就是为什么它们是静态的。 换句话说,你永远不需要明确地打电话,如果你这样做,通过反思说(我不知道它是否会让你),那么你做错了什么。

当你创build一个新的类的实例时,构造函数的存在是为了初始化他所有的内部variables,并且按照预期的方式进行任何types的处理。 注意,如果你不指定一个构造函数,编译器会为你创build一个构造函数。 出于这个原因,你仍然需要像这样创build一个类“()”

  new MyClass(); 

因为你正在调用默认的构造函数(假设你没有定义一个无参数的构造函数)。 换句话说,非静态构造函数被定义为public的原因是因为你需要明确地调用它。 如果内存为我提供了很好的帮助,那么C#将不会在尝试调用未通过malloc定义的构造函数的代码上进行编译。

静态类中的构造函数是为了“设置”目的而存在的。 例如,我可以有一个静态类,应该是我的代码和我不断保存和读取数据的文件之间的桥梁。 我可以定义一个构造函数,一旦创build对象,将确保文件存在,如果不创build一个默认的(在Web系统中移植到其他服务器非常有帮助)。

 using System; public class Something { // private static DateTime _saticConstructorTime; private DateTime _instanceConstructorTime; // public static DateTime SaticConstructorTime { set { _saticConstructorTime = value; } get { return _saticConstructorTime ; } } public DateTime InstanceConstructorTime { set { _instanceConstructorTime = value; } get { return _instanceConstructorTime; } } //Set value to static propriety static Something() { SaticConstructorTime = DateTime.Now; Console.WriteLine("Static constructor has been executed at: {0}", SaticConstructorTime.ToLongTimeString()); } //The second constructor started alone at the next instances public Something(string s) { InstanceConstructorTime = DateTime.Now; Console.WriteLine("New instances: "+ s +"\n"); } public void TimeDisplay(string s) { Console.WriteLine("Instance \""+ s + "\" has been created at: " + InstanceConstructorTime.ToLongTimeString()); Console.WriteLine("Static constructor has been created at: " + SaticConstructorTime.ToLongTimeString() + "\n"); } } // class Client { static void Main() { Something somethingA = new Something("somethingA"); System.Threading.Thread.Sleep(2000); Something somethingB = new Something("somethingB"); somethingA.TimeDisplay("somethingA"); somethingB.TimeDisplay("somethingB"); System.Console.ReadKey(); } } /* output : Static constructor has been executed at: 17:31:28 New instances: somethingA New instances: somethingB Instance "somethingA" has been created at: 17:31:28 Static constructor has been created at: 17:31:28 Instance "somethingB" has been created at: 17:31:30 Static constructor has been created at: 17:31:28 */