[英]c# static constructor not called from derived class
class Bus<T>
{
static Bus()
{
foreach(FieldInfo fi in typeof(T).GetFields())
{
if(fi.FieldType == typeof(Argument))
{
fi.SetValue(typeof(T), new Argument("busyname", "busyvalue"));
}
}
}
}
class Buss : Bus<Buss>
{
public static Argument field;
}
Any ideas how to make this work so that a reference to the static field in Buss triggers the static constructor in Bus? 任何想法如何使这个工作,以便Buss中的静态字段的引用触发总线中的静态构造函数?
The fact that this matters to you probably means that you are using static constructors wrong. 这对你很重要的事实可能意味着你使用静态构造函数是错误的。
With that in mind, you could make a static constructor in Buss
that manually invokes the static constructor in Bus
. 考虑到这一点,您可以在
Buss
中创建一个静态构造函数,手动调用Bus
的静态构造函数。 Note that it's not possible to run a static constructor more than once. 请注意,不可能多次运行静态构造函数。
The static constructor of a generic type is invoked exactly once per Type
, when that type is referenced. 当引用该类型时,每个
Type
只调用一次泛型类型的静态构造函数。
Calling Buss x = new Buss()
will invoke the static constructor of Bus<Buss>
. 调用
Buss x = new Buss()
将调用Bus<Buss>
的静态构造函数。
Calling Bus<Buss> x = new Bus<Buss>()
will also invoke the static constructor of Bus<Buss>
, but it will do so for it's type argument Buss
, setting Buss.field
. 调用
Bus<Buss> x = new Bus<Buss>()
也将调用Bus<Buss>
的静态构造函数,但它将为其类型参数Buss
,设置Buss.field
。
If you create a class Bugs : Bus<Buss>
it will never set Bugs.field
, as it will first resolve the type argument Buss
, which invokes the static constructor of it's base class Bus<Buss>
, setting Buss.field
. 如果你创建一个
class Bugs : Bus<Buss>
它将永远不会设置Bugs.field
,因为它将首先解析类型参数Buss
,它调用它的基类Bus<Buss>
的静态构造函数,设置Buss.field
。 When it tries to call the static constructor of Bugs
base class, it will think it had already invoked the static Bus<Buss>
constructor and skip it. 当它试图调用
Bugs
基类的静态构造函数时,它会认为它已经调用了静态Bus<Buss>
构造函数并跳过它。
Basically if I copy paste your code, create a dummy Argument
class and create a new instance of Buss
, the static constructor is invoked and Buss.field
is set to an instance of Argument
, but I do recognize some strange behavoir here in which I'd have to advise not to use reflection from a static method to reach subclasses' statics. 基本上,如果我复制粘贴代码,创建一个虚拟的
Argument
类,并创建一个新的实例Buss
,静态构造函数被调用, Buss.field
设置为实例Argument
,但我在这里认识了一些奇怪的behavoir在我d必须建议不要使用静态方法的反射来达到子类的静态。
The example you provided only works because Buss
is the type argument for itself. 您提供的示例仅起作用,因为
Buss
是其自身的类型参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.