简体   繁体   English

C#在类加载上加载静态方法

[英]C# Load a static method on class load

I have a set of static variables 我有一组静态变量

static string A;
static string B;
static string C;
...

that I would like to initialize. 我想初始化。

Now, I could do 现在,我能做到

static string A;
...
static string Z = InitializeAllVariables();

static void InitializeAllVariables()
{
     /// Initialize all my static variables
}

but that's not very elegant. 但那不是很优雅。

Is there a way to force InitializeAllVariables() to run on class load so that I don't need to explicitly call it through a static variable definition? 有没有办法强制InitializeAllVariables()在类加载上运行,这样我就不需要通过静态变量定义显式调用它?

Thanks. 谢谢。

Use a static constructor. 使用静态构造函数。

public static class MyClass
{
    static string A;
    static string B;
    static string C;

    static MyClass()
    {
        A = "Hello";
        B = "World";
        C = "!";
    }
}

Use the static constructor: 使用静态构造函数:

static MyClass() {

}

This should do: 这应该做:

Static SomeClass()
{
   InitializeAllVariables();
}

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

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