C#中的静态构造函数

我试图使用如下的静态构造函数:
public static DataManager()
{
    LastInfoID = 1;
}
并收到此错误:   静态构造函数不允许访问修饰符 我想知道我的问题是什么。     
已邀请:
静态构造函数没有访问修饰符:它只是:
static DataManager() // note no "public"
{
    LastInfoID = 1;
}
这是因为它永远不会被显式调用(除非可能通过反射) - 但是由运行时调用;访问级别将毫无意义。     
问题是
LastInfoID
字段或属性在类中未声明为静态,您只能从静态构造函数中访问静态成员。同时从声明中删除
public
关键字:
static DataManager()
{
    LastInfoID = 1;
}
    
删除
public
。静态构造函数的语法是:
class MyClass 
{
    static MyClass() 
    {
        // Static constructor
    }
}
    
为了给这里的任何人一个更清晰的答案,没有一个例子,想一想为什么你必须从外面访问静态构造函数?在应用程序执行时,会在内存中创建静态类,这就是它们是静态的原因。换句话说,你永远不需要明确地调用一个,如果你这样做,通过反射说(我不知道它是否会让你),那么你做错了。 当您创建类的新实例时,构造函数作为初始化所有内部变量的方式存在,并进行必要的任何处理以使类按预期方式运行。请注意,如果您未指定构造函数,编译器将为您创建一个构造函数。因此,您仍然需要创建一个类似“()”的类
     new MyClass();
因为您正在调用默认构造函数(前提是您没有定义无参数构造函数)。换句话说,必须将非静态构造函数定义为public的原因是因为您需要显式调用它。如果内存对我很好,C#将无法编译试图调用未定义为public的(通过malloc)构造函数的代码。 静态类中的构造函数用于“设置”目的。例如,我可以有一个静态类,它应该是我的代码和我不断保存并从中读取数据的文件之间的桥梁。我可以定义一个构造函数,在创建对象时,它将确保文件存在,如果不存在则创建默认文件(在移植到其他服务器的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
 */
    

要回复问题请先登录注册