静态代码块 [英] Static code blocks
问题描述
从 Java
到 C#
,我有以下问题:在Java中,我可以执行以下操作:
Going from Java
to C#
I have the following question:
In java I could do the following:
public class Application {
static int attribute;
static {
attribute = 5;
}
// ... rest of code
}
我知道我可以从构造函数中初始化它,但这不符合我的需要(我想在不创建对象的情况下初始化并调用一些实用程序函数).C#是否支持此功能?如果是,我该怎么做?
I know I can initialize this from the constructor but this does not fit my needs (I want to initialize and call some utility functions without create the object). Does C# support this? If yes, how can I get this done?
预先感谢
推荐答案
public class Application
{
static int attribute;
static Application()
{
attribute = 5;
} // removed
}
You can use the C# equivalent static constructors. Please don't confuse it with a regular constructor. A regular constructor doesn't have a static
modifier in front of it.
我假设您的//...其余代码
也需要运行一次.如果您没有这样的代码,则只需执行此操作即可.
I am assuming your //... rest of the code
need to be also run once. If you don't have such code you can just simply do this.
public class Application
{
static int attribute = 5;
}
这篇关于静态代码块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!