.Net:访问常量时是否会调用静态构造函数?
所以这就是我的想法......
public class MyClass
{
public const string MyConstant = "MyConstantValue";
private static MyClass DefaultInstance;
static MyClass()
{
DefaultInstance = new MyClass();
}
}
...
NotificationService.RegisterForNotification(MyClass.MyConstant, Callback);
这行得通还是我需要使用诸如 static readonly
property 字段之类的东西来触发静态构造函数?
So here is what I'm thinking...
public class MyClass
{
public const string MyConstant = "MyConstantValue";
private static MyClass DefaultInstance;
static MyClass()
{
DefaultInstance = new MyClass();
}
}
...
NotificationService.RegisterForNotification(MyClass.MyConstant, Callback);
Will this work or do I need to use something like a static readonly
property field to trigger the static constructor?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用常量不一定会导致成员访问,这会导致调用静态构造函数。编译器被允许(甚至鼓励)在编译时替换常量的值。
尽管
readonly
建议使用字段,而不是属性,但您建议的static readonly
解决方法应该没问题。当属性没有 setter 时,它们是只读的,不涉及readonly
关键字。一个简单的例子:
.NET 4.0下的输出:
静态构造函数永远不会运行!
Use of a constant doesn't necessarily result in a member access which would cause the static constructor to be called. The compiler is allowed to (encouraged, even) substitute the value of the constant at compile time.
Your suggested workaround of
static readonly
should be ok, althoughreadonly
suggests a field, not a property. Properties are read-only when they have no setter, thereadonly
keyword isn't involved.A simple example:
Output under .NET 4.0:
The static constructor never runs!
在创建第一个实例或引用任何静态成员之前,会自动调用静态构造函数。请参阅此处:MSDN:静态构造函数
顺便说一句,常量字段本质上是静态的,但正如所指出的,它们可以(并且可能会)被值本身替换。
Static constructor is called automatically before the first instance is created or any static members are referenced. See here: MSDN: Static Constructors
By the way, constant fields are inherently static, but as pointed they may (and probably will) be substituted by the value itself.
如果您只是访问公共常量,则不会调用静态构造函数。例如,考虑这个类:
现在,在另一个类中,执行:
您的输出将是:
常量在编译时从类中提升。因此,
Testo.MyValue
的值在运行时不会引用Testo
类。在调用需要初始化的内容之前,不会调用静态构造函数。因此,是的,如果您想确保调用构造函数,则需要访问类似
static readonly
的内容。The static constructor will not be called if you're just accessing public constants. For example, consider this class:
Now, in another class, execute:
Your output will be:
Constants are hoisted from the class at compile time. So the value of
Testo.MyValue
does not reference theTesto
class at runtime. The static constructor is not called until you call something that requires initialization.So, yes, you need to access something like a
static readonly
if you want to ensure that the constructor is called.不,你不需要这样的。静态构造函数在类加载时被调用。
No, you don't need such. Static constructor is called when the class is loaded.