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

后端 未结 6 1160
囚心锁ツ
囚心锁ツ 2020-12-02 15:16

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

6条回答
  •  北海茫月
    2020-12-02 15:45

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

    // this prints "False"
    Console.WriteLine(typeof(Foo) == typeof(Foo));
    

    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 and Foo 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.

提交回复
热议问题