C# 静态构造函数不从派生类调用
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;
}
有什么想法如何使其工作,以便对 Buss 中的静态字段的引用触发 Bus 中的静态构造函数?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这对您来说很重要,这一事实可能意味着您错误地使用了静态构造函数。
考虑到这一点,您可以在
Buss
中创建一个静态构造函数,手动调用Bus
中的静态构造函数。请注意,静态构造函数不能多次运行。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 inBus
. Note that it's not possible to run a static constructor more than once.当引用该类型时,每个
Type
都会调用泛型类型的静态构造函数一次。调用
Buss x = new Buss()
将调用Bus
的静态构造函数。调用
Bus; x = new Bus()
还将调用Bus
的静态构造函数,但它会针对其类型参数Buss
执行此操作,设置Buss.field。如果您创建一个
class Bugs : Bus
它永远不会设置Bugs.field
,因为它会首先解析类型参数Buss
,它调用其基类Bus
的静态构造函数,设置Buss.field
。当它尝试调用Bugs
基类的静态构造函数时,它会认为它已经调用了静态Bus
构造函数并跳过它。基本上,如果我复制粘贴您的代码,创建一个虚拟
Argument
类并创建一个Buss
的新实例,则调用静态构造函数并Buss.field
被设置为Argument
的实例,但我确实认识到这里有一些奇怪的行为,我不得不建议不要使用反射从静态方法到达子类的静态。您提供的示例仅有效,因为 Buss 是其自身的类型参数。
The static constructor of a generic type is invoked exactly once per
Type
, when that type is referenced.Calling
Buss x = new Buss()
will invoke the static constructor ofBus<Buss>
.Calling
Bus<Buss> x = new Bus<Buss>()
will also invoke the static constructor ofBus<Buss>
, but it will do so for it's type argumentBuss
, settingBuss.field
.If you create a
class Bugs : Bus<Buss>
it will never setBugs.field
, as it will first resolve the type argumentBuss
, which invokes the static constructor of it's base classBus<Buss>
, settingBuss.field
. When it tries to call the static constructor ofBugs
base class, it will think it had already invoked the staticBus<Buss>
constructor and skip it.Basically if I copy paste your code, create a dummy
Argument
class and create a new instance ofBuss
, the static constructor is invoked andBuss.field
is set to an instance ofArgument
, 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.The example you provided only works because
Buss
is the type argument for itself.MSDN 说“静态构造函数是没有继承'。我想这类似于也不继承的静态字段。
MSDN says that 'Static constructors are not inherited'. I guess this is similar to static fields which are not inherited either.