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

标签 c#

我有一组静态变量

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

我想初始化。

现在,我可以做

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

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

但这不是很优雅。

有没有办法强制 InitializeAllVariables() 在类加载时运行,这样我就不需要通过静态变量定义显式调用它?

谢谢。

最佳答案

使用静态构造函数。

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

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

关于C# 在类加载时加载静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17663608/

相关文章:

c# 使用 linq 将 viewModel List 对象上的字符串属性串联起来显示在 MVC View 上

c# - 在 C# 中移动文件之前等待获得文件的独占访问权限

c# - 以编程方式设置防止意外删除 Microsoft Active Directory 中的 ou

c# - Windows 8 中的墙纸注册表项在哪里?

c# - 在 .Net 中创建提醒服务的最佳方式是什么?

c# - 如何在 C# 中编码指向数组的指针

c# - IEnumerable Group 按用户指定的动态键列表

c# windows 服务配置文件

c# - 如何返回满足条件 C# 的 ObservableCollection 中的所有项目

c# - 在 C# 测试中从 Json 文件中读取和映射数据