fwe*_*aks 0 c# static-methods static-constructor readonly-variable
我的一个类有一个相当大的静态构造函数,并且想要重构它以将初始化的各个部分封装在静态函数中。
One of the things this static constructor does a lot of is initialize the values of static readonly fields. However, when I try to move these parts into functions, obviously the compiler wont let me as these can only be set in the static constructor. This makes sense as it doesn't know that I only intend to call these functions from my static constructor.
Is there any way around this? e.g. is there some sort of attribute I can put on the functions to tell the compiler the functions are only to be called from the static constructor?
您可以在静态构造函数中定义局部函数;
public class MyClass {
public static readonly int Value;
static MyClass(){
Value = Calc(1);
return;
int Calc(int a) => a;
}
}
Run Code Online (Sandbox Code Playgroud)
C# 编译器会将这些本地函数转换为静态方法,并具有难以发音的名称。