是一个静态成员变量共同为所有的C#泛型实例? [英] Is a static member variable common for all C# generic instantiations?

查看:381
本文介绍了是一个静态成员变量共同为所有的C#泛型实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#我有一个泛型类:

In C# I have a generic class:

public class MyGeneric<ParameterClass> where ParameterClass: MyGenericParameterClass, new() {
    public static int Variable;
}

现在在C ++中,如果我实例化的不同参数的模板类的每个完整的类将得到它自己的变量,所以我不能说

Now in C++ if I instantiated a templated class with different parameters each complete class would get it's own Variable, so I just can't say

MyGeneric.Variable = 1; // invalid in C++

在C ++中,但好像我可以在C#这样做。

in C++, but seems like I can do so in C#.

我想澄清......

I'd like to clarify...

如果我有一个通用的一个静态成员变量是共享变量所有通用的实例中?

If I have a generic with a static member variable is that variable shared among all generic instantiations?

推荐答案

Section的ECMA C#语言规范的25.1.4

在一个通用的静态变量类声明的其中包括
共享同一个封闭构造类型(§26.5.2)的所有实例,而不是不同之间封闭构造类型的实例共享

无论静态
变量的类型是否涉及任何类型的参数或没有这些规则适用。

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.

您可能会看到这篇博客文章:通过的的泛型类静态字段= http://social.msdn.microsoft.com/profile/gus%20perez/\">Gus佩雷斯

You may see this blog post: Static fields in generic classes by Gus Perez

您不能这样做,在C#为好。

You can't do that in C# as well.

MyGeneric.Variable = 1;



考虑从ECMA语言规范下面的例子。

Consider the following example from ECMA Language Specification.

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#泛型实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆