C # static in abstract superclass will be split between subclasses?

I am writing several ashx handlers that are connected to the layout, and I want them to share an instance of the mock service. The simplest approach, although I created a static instance

public class AbstractHandler
    {
        static IService _impl;
        public static IService Impl
        {
            get
            {
                if (_impl == null)
                {
                    _impl = new MockService();
                }
                return _impl;
            }
        }
    }

However, I wonder if this will work at all; will different handlers inherited from this class have their own static link _impl or will they be available?

+3
source share
1 answer

A static field exists once, except in the case of a general type, in which case it exists once for each combination of common parameters used.

, , , . : , , , , . " ..." , , , .

, :

,

, .

LINQPad script, " ":

void Main()
{
    var i = new Test<int>();
    var s = new Test<string>();

    Test<bool>.UsageCount.Dump();
    Test<int>.UsageCount.Dump();
    Test<string>.UsageCount.Dump();
}

public class Test<T>
{
    public static int UsageCount;

    public Test()
    {
        UsageCount++;
    }
}

:

0
1
1

:

void Main()
{
    var i = new Test1();
    var s = new Test2();

    Test1.UsageCount.Dump();
    Test2.UsageCount.Dump();
    Test3.UsageCount.Dump();
}

public abstract class Base<T>
{
    public static int UsageCount;

    protected Base()
    {
        UsageCount++;
    }
}

public class Test1 : Base<Test1>
{
}

public class Test2 : Base<Test2>
{
}

public class Test3 : Base<Test3>
{
}

:

1
1
0
+6

All Articles