gpt4 book ai didi

c# - 继承静态成员的静态初始化

转载 作者:太空狗 更新时间:2023-10-29 21:40:29 31 4
gpt4 key购买 nike

考虑这个示例代码:

public class A<T> 
{
public static T TheT { get; set; }
}
public class B : A<string>
{
static B() {
TheT = "Test";
}
}

public class Program {
public static void Main(String[] args) {
Console.WriteLine(B.TheT);
}
}

此处 B.TheT 为空。但是,像这样更改 Main 方法:

public static void Main() {
new B();
Console.WriteLine(B.TheT);
}

B.TheT 正如预期的那样是“测试”。我可以理解这会强制静态构造函数运行,但为什么第一种情况不会发生这种情况?

我尝试阅读规范,这引起了我的注意 (§10.12):

[...] The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

• [...]

• Any of the static members of the class type are referenced.

我对此的解释是,由于 TheT 不是 B 的成员,因此不会强制运行 B 的静态构造函数.这是正确的吗?

如果那是正确的,我如何最好地让 B 指定如何初始化 TheT

最佳答案

A.TheT is "Test", as expected. I can understand that this forces the static constructor to run, but why does this not happen for the first case?

基本上,您还没有真正引用B。如果您查看 IL,我想您会发现您的代码实际上等同于:

public static void Main(String[] args) {
Console.WriteLine(A<string>.TheT);
}

即使您编写了 B.TheT,编译器仍然确实是您所指的成员。

If that is correct, how would I best let A specify how to initialize TheT?

老实说,我一开始会尽量避免这样做......但你总是可以向 B 添加一个静态方法:

public static void Initialize() {
// Type initializer will be executed now.
}

关于c# - 继承静态成员的静态初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12953797/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com