Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

c# - Are static members of a generic class tied to the specific instance?

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;
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>));

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...