[英]C# What is the difference between creating a static object outside a class VS creating it inside a class?
I want to understand the difference between 3 sets of snippets below: 我想了解以下3组摘要之间的区别:
private static FirstObject o = new FirstObject();
public class ClassA
{
}
//-----------------------------------------------------
public class ClassA
{
private static FirstObject o = new FirstObject();
}
//-----------------------------------------------------
public class ClassA
{
private static FirstObject o;
public ClassA
{
o = new FirstObject();
}
}
Please help me understand in terms of scope, memory, performance and usage of these. 请帮助我了解这些工具的范围,内存,性能和用法。
Thank you. 谢谢。
Invalid, as you can't have a variable outside of object 无效,因为您不能在对象外部有变量
The proper way - the class has a static member, which is initialized when the class is accessed for the first time 正确的方法-该类具有静态成员,该静态成员在首次访问该类时初始化
Very bad, because every time when new object is created the static object will be recreated. 非常糟糕,因为每次创建新对象时,都会重新创建静态对象。
The first option will not compile. 第一个选项将无法编译。 A static variable in C# must be scoped to a class or struct.
C#中的静态变量必须作用域为类或结构。
The second option is the preferred mechanism. 第二种选择是首选机制。
The third option is wrong because this creates a new FirstObject
each time an instance of ClassA
is created, which is almost certainly not what you want. 第三个选项是错误的,因为每次创建
ClassA
实例时都会创建一个新的FirstObject
,这几乎肯定不是您想要的。
A fourth option would be to leverage a static constructor, eg, 第四个选择是利用静态构造函数,例如,
public class ClassA
{
private static FirstObject o;
static ClassA
{
o = new FirstObject();
}
}
This option is useful if there is some special construction constraints for FirstObject
. 如果
FirstObject
有一些特殊的构造约束,则此选项很有用。 In this example, though, choose option 2 over option 4. Just know that option 4 exists. 但是,在此示例中,选择选项2而不是选项4。只知道选项4存在。
Three cases below... 以下三种情况...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.