C# · 12月 31, 2021

所有C#通用实例的静态成员变量是常用的?

在C#中我有一个泛型类: public class MyGeneric<ParameterClass> where ParameterClass: MyGenericParameterClass,new() { public static int Variable;}

现在在C中,如果我实例化了一个不同参数的模板类,那么每个完整的类都会得到它自己的变量,所以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 by 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 }}