从Java到C#,我有以下问题:在java中,我可以做到以下几点:
public class Application {
static int attribute;
static {
attribute = 5;
}
// ... rest of code
}我知道我可以从构造函数初始化它,但这不符合我的需要(我想初始化并调用一些实用函数,而不创建对象)。C#是否支持这一点?如果是,我该如何完成这项工作?
提前谢谢你,
发布于 2011-12-11 03:11:18
public class Application
{
static int attribute;
static Application()
{
attribute = 5;
} // removed
}您可以使用与C#等效的static constructors。请不要将其与常规构造函数混淆。常规构造函数前面没有static修饰符。
我假设您的//... rest of the code也需要运行一次。如果你没有这样的代码,你可以简单地这样做。
public class Application
{
static int attribute = 5;
}发布于 2011-12-11 03:12:39
你可以像这样写一个静态的构造函数块,
static Application(){
attribute=5;
}这就是我能想到的。
发布于 2011-12-11 03:16:32
在您的特定场景中,您可以执行以下操作:
public class Application {
static int attribute = 5;
// ... rest of code
}更新:
听起来你想要调用一个静态方法。您可以按如下方式执行此操作:
public static class Application {
static int attribute = 5;
public static int UtilityMethod(int x) {
return x + attribute;
}
}https://stackoverflow.com/questions/8459095
复制相似问题