在 C# 中我有一个泛型类:
public class MyGeneric<ParameterClass> where ParameterClass: MyGenericParameterClass, new() {
public static int Variable;
}
现在在 C++ 中,如果我用不同的参数实例化一个模板类,每个完整的类都会得到它自己的 Variable
,所以 I just can't say
MyGeneric.Variable = 1; // invalid in C++
在 C++ 中,但似乎我可以在 C# 中这样做。
我想澄清...
如果我有一个带有静态成员变量的泛型,该变量是否在所有泛型实例化之间共享?
最佳答案
Section 25.1.4 of the ECMA C# Language specification
A static variable in a generic class declaration is shared amongst all instances of the same closed constructed type (§26.5.2), but is not shared amongst instances of different closed constructed types. These rules apply regardless of whether the type of the static variable involves any type parameters or not.
您可能会看到这篇博文:Static fields in generic classes通过 Gus Perez
您也不能在 C# 中执行此操作。
MyGeneric.Variable = 1;
考虑 ECMA 语言规范中的以下示例。
class C<V>
{
static int count = 0;
public C()
{
count++;
}
public static int Count
{
get { return count; }
}
}
class Application
{
static void Main()
{
C<int> x1 = new C<int>();
Console.WriteLine(C<int>.Count); // Prints 1
C<double> x2 = new C<double>();
Console.WriteLine(C<double>.Count); // Prints 1
Console.WriteLine(C<int>.Count); // Prints 1
C<int> x3 = new C<int>();
Console.WriteLine(C<int>.Count); // Prints 2
}
}
关于c# - 静态成员变量是否对所有 C# 泛型实例化都是通用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14748569/