泛型类的静态成员是否绑定到特定实例? [英] Are static members of a generic class tied to the specific instance?
问题描述
这与其说是一个真正的问题,不如说是一个文档.这似乎还没有在 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?
它可以很容易地通过这样的代码验证:
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?
推荐答案
static
字段在所有相同类型的实例之间共享.Foo
和 Foo
是两种不同的类型.这可以通过以下代码行来证明:
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>));
至于记录的位置,可在 C# 语言规范(针对 C# 3)的 1.6.5 字段 部分中找到以下内容:
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.
如前所述;Foo
和 Foo
不是同一个类;它们是由同一个泛型类构造的两个不同的类.上述文档的第 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屋!