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

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

    They are not really shared. Because the member doesn't belong to the instance at all. A static class member belongs to the class itself. So, if you have MyClass.Number it is the same for all MyClass.Number objects because it not even depends on the object. You can even call or modify MyClass.Number without any object.

    But since Foo< int > is not the same class as Foo< string > these two numbers are not shared.

    An example to show this:

    TestClass.Number = 5;
    TestClass.Number = 3;
    
    Console.WriteLine(TestClass.Number);  //prints 5
    Console.WriteLine(TestClass.Number);     //prints 3
    

提交回复
热议问题