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

后端 未结 6 1161
囚心锁ツ
囚心锁ツ 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:49

    C# implementation of generics is more closer to C++. In both of these languages MyClass and MyClass don't share static members but in Java they do. In C# and C++ MyClass internally creates entirely new type at compile time as if generics are kind of macros. You can usually see their generated names in stack trace, like MyClass'1 and MyClass'2. This is why they don't share static variables. In Java, generics are implemented by more simpler method of compiler generating code using non-generic types and adding type casts all over. So MyClass and MyClass don't generate two entirely new class in Java, instead they both are same class MyClass underneath and that's why they share static variables.

提交回复
热议问题