加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:49:36 所属栏目:百科 来源:网络整理
导读:在C#中我有一个泛型类: public class MyGenericParameterClass where ParameterClass: MyGenericParameterClass,new() { public static int Variable;} 现在在C中,如果我实例化了一个不同参数的模板类,那么每个完整的类都会得到它自己的变量,所以I just can
在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 
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读