简体   繁体   English

C#中的静态构造函数

[英]Static constructor in C#

I am trying to use a static constructor like the following: 我试图使用如下的静态构造函数:

public static DataManager()
{
    LastInfoID = 1;
}

and getting this error: 并收到此错误:

access modifiers are not allowed on static constructors 静态构造函数不允许访问修饰符

I would like to know what's my problem. 我想知道我的问题是什么。

The static constructor has no access modifier: it is just: 静态构造函数没有访问修饰符:它只是:

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

This is because it is never called explicitly (except perhaps via reflection) - but is invoked by the runtime; 这是因为它永远不会被显式调用(除非可能通过反射) - 但是由运行时调用; an access-level would be meaningless. 访问级别将毫无意义。

The problem is that the LastInfoID field or property is not declared as static in your class and you can access only static members from a static constructor. 问题是LastInfoID字段或属性在类中未声明为static ,您只能从静态构造函数访问静态成员。 Also remove the public keyword from the declaration: 同时从声明中删除public关键字:

static DataManager()
{
    LastInfoID = 1;
}

Remove the public . 删除public The syntax for a static constructor is: 静态构造函数的语法是:

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

To give anyone here a more clear answer, without an example, think about why you would have to access a static constructor from outside? 为了给这里的任何人一个更清晰的答案,没有一个例子,想一想为什么你必须从外面访问静态构造函数? Static classes are created in memory upon application execution, that is why they are static. 在应用程序执行时,会在内存中创建静态类,这就是它们是静态的原因。 In other words, you would NEVER need to call one explicitly and if you do, say through reflection (which I don't know if it will let you), then you are doing something wrong. 换句话说,你永远不需要明确地调用一个,如果你这样做,通过反射说(我不知道它是否会让你),那么你做错了。

When you create a new instance of a class, the constructor exists as a way to initialize all he internal variables and to do any kind of processing necessary to make the class function the way it is intended. 当您创建类的新实例时,构造函数作为初始化所有内部变量的方式存在,并进行必要的任何处理以使类按预期方式运行。 Notice, if you do not specify a constructor the compiler will create one for you. 请注意,如果您未指定构造函数,编译器将为您创建一个构造函数。 For this reason you still need to create a class with a "()" like so 因此,您仍然需要创建一个类似“()”的类

     new MyClass();

because you are calling the default constructor (provided you do not have a parameterless one defined). 因为您正在调用默认构造函数(前提是您没有定义无参数构造函数)。 In other words, the reason why a non-static constructor has to be defined as public is because you need to call it explicitly. 换句话说,必须将非静态构造函数定义为public的原因是因为您需要显式调用它。 If memory serves me well, C# will not compile on code that attempts to call a (through malloc) constructor that is not defined as public. 如果内存对我很好,C#将无法编译试图调用未定义为public的(通过malloc)构造函数的代码。

Constructors in a static class exist for "setup" purposes. 静态类中的构造函数用于“设置”目的。 For instance I can have a static class that is supposed to be the bridge between my code and a file that I am constantly saving and reading data from. 例如,我可以有一个静态类,它应该是我的代码和我不断保存并从中读取数据的文件之间的桥梁。 I can define a constructor that, upon object creation, will make sure that the file exists and if not creates a default one (very help full in web systems that are ported to other servers). 我可以定义一个构造函数,在创建对象时,它将确保文件存在,如果不存在则创建默认文件(在移植到其他服务器的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
 */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM