c# - 静态成员变量是否对所有 C# 泛型实例化都是通用的?

标签 c# generics static-variables

在 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/

相关文章:

c# - WCF 客户端异常 : Unrecognized message version

java - 使用静态变量来打破递归

c# - Linux VPS 上的单声道垃圾收集

java - 两种创建具有相同结果的泛型数组的方法,但只有一种有效

swift - 扩展泛型类型别名

java - Eclipse(或任何 IDE)能否将类型参数引入现有类型

c - 在这个递归场景中,这个静态变量的作用是什么?

objective-c - 静态变量和类扩展中的变量有什么区别?

java - 使用 Java WSDL、Enum 和 Boolean 属性的 C# 不会根据请求发送

c# - C# 中通过引用传递值的语法问题