Do static locks work across different children classes?

后端 未结 3 1306
轮回少年
轮回少年 2021-01-05 10:05

If I have

abstract class Parent
{
    static object staticLock = new object();

    public void Method1()
    {
        lock(staticLock)
        {
                   


        
3条回答
  •  走了就别回头了
    2021-01-05 10:06

    Yes. A derived class does not get a new copy of the static data from the base class.

    However, this is not the case with generic classes. If you say:

    class Base
    {
        protected static object sync = new object();
        ...
    }
    
    class Derived1 : Base { ... }
    class Derived2 : Base { ... }
    class Derived3 : Base { ... }
    class Derived4 : Base { ... }
    class Derived5 : Base { ... }
    class Derived6 : Base { ... }
    
    
    

    instances of Derived1 and Derived2 have the same sync object. Instances of Derived3 and Derived4 have the same sync object. Instances of Derived5 and Derived6 have the same sync object. But the three sync objects are all different objects.

    提交回复
    热议问题