是一个泛型类的静态成员联系在一起的具体实例? [英] Are static members of a generic class tied to the specific instance?

查看:220
本文介绍了是一个泛型类的静态成员联系在一起的具体实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是更多的是文档比真正的问题。这似乎并没有得到解决的SO,但(除非我错过了),所以这里有云:

This is more of a documentation than a real question. This does not seem to have been addressed on SO yet (unless I missed it), so here goes:

想象一个包含静态成员泛型类:

Imagine a generic class that contains a static member:

class Foo<T> {
    public static int member;
}

是否有每个特定类的成员的一个新实例,或者是有仅用于所有的Foo型类的单个实例

Is there a new instance of the member for each specific class, or is there only a single instance for all Foo-type classes?

它可以很容易地通过code证实是这样的:

It can easily be verified by code like this:

Foo<int>.member = 1;
Foo<string>.member = 2;
Console.WriteLine (Foo<int>.member);

结果是什么,哪里是这种行为记录?

What is the result, and where is this behavior documented?

推荐答案

A 静态字段是所有实例共享的的同类型的。 美孚&LT; INT&GT; 美孚&LT;字符串&GT; 两种不同的类型。这可以通过code以下行来证明:

A static field is shared across all instances of the same type. Foo<int> and Foo<string> are two different types. This can be proven by the following line of code:

// this prints "False"
Console.WriteLine(typeof(Foo<int>) == typeof(Foo<string>));

至于在哪里,这是记录在案,下面是部分的 1.6.5字段的C#语言规范中(对于C#3):

As for where this is documented, the following is found in section 1.6.5 Fields of the C# Language Specification (for C# 3):

一个静态字段只标识一个   存储位置。不管有多少   创建类的实例,   还有的只有永远一个副本   静态字段。

A static field identifies exactly one storage location. No matter how many instances of a class are created, there is only ever one copy of a static field.

如前所述; 美孚&LT; INT&GT; 美孚&LT;字符串&GT; 不是同一类;它们是从同一个通用类构成两个不同的类。在上述文​​件中4.4节是怎么发生这种情况概述:

As stated before; Foo<int> and Foo<string> are not the same class; they are two different classes constructed from the same generic class. How this happens is outlined in section 4.4 of the above mentioned document:

一个泛型类型声明,其本身   表示未绑定的泛型类型   用作蓝图,以形成许多   不同的类型,通过施加方式   类型参数。

A generic type declaration, by itself, denotes an unbound generic type that is used as a "blueprint" to form many different types, by way of applying type arguments.

这篇关于是一个泛型类的静态成员联系在一起的具体实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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