静态代码块

GET*_*Tah 63 .net c# static

从去JavaC#在java中我可以做到以下几点:我有以下问题:

public class Application {
    static int attribute;
    static {
        attribute = 5;
    }
   // ... rest of code
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以从构造函数初始化它,但这不符合我的需要(我想初始化并调用一些实用程序函数而不创建对象).C#支持这个吗?如果是,我该如何完成?

提前致谢,

par*_*mar 118

public class Application
{     

    static int attribute;     
    static Application()
    {         
         attribute = 5;     
    }    // removed
}
Run Code Online (Sandbox Code Playgroud)

您可以使用C#等效的静态构造函数.请不要将它与常规构造函数混淆.常规构造函数static前面没有修饰符.

我假设你//... rest of the code需要也跑一次.如果您没有这样的代码,您可以简单地执行此操作.

 public class Application
 {     

    static int attribute = 5;
 }
Run Code Online (Sandbox Code Playgroud)

  • @GETah它不会......注意`静态` (3认同)

Aja*_*jai 12

你可以像这样写一个静态构造函数块,

static Application(){
 attribute=5;
}
Run Code Online (Sandbox Code Playgroud)

这是我能想到的.

  • @GETah:不会,因为使用了 static 关键字。 (2认同)