スーパークラスは、C#で各サブクラスごとに異なるの静的変数を持って作ります

StackOverflow https://stackoverflow.com/questions/1843114

質問

のサブクラスの中の任意のコードがなければ、私は、各サブクラスの静的変数の別のコピーを持つように抽象クラスをしたいと思います。 C#での

abstract class ClassA
{
    static string theValue;

    // just to demonstrate
    public string GetValue()
    {
        return theValue;
    }
    ...
}
class ClassB : ClassA { }
class ClassC : ClassA { }

と(例えば):

(new ClassB()).GetValue(); // returns "Banana"
(new ClassC()).GetValue(); // returns "Coconut"

私の現在のソリューションはこれです:

abstract class ClassA
{
    static Dictionary<Type, string> theValue;
    public string GetValue()
    {
        return theValue[this.GetType()];
    }
    ...
}

これは正常に動作しますが、これを行うためのよりエレガントまたは組み込みの方法があります場合、私は思ったんだけど?

これは私がclass">をすることができ継承のそれぞれ異なるタイプの静的変数の異なるコピーを持っている

他のヒント

よりエレガントな方法があります。あなたは、一般的な基本クラスの静は、異なるタイプの各派生クラス

のために異なっているという事実を利用することができます
public abstract class BaseClass<T> where T : class
{
    public static int x = 6;
    public int MyProperty { get { return x; } set { x = value; } }
}

それぞれの子クラスの場合、静的なint型のxは、それぞれユニークなTに対して一意になります 2つのクラスを派生することができます、と私たちは、基本クラスでの一般的なTとして子クラスの名前を使用します。

public class ChildA: BaseClass<ChildA>
{
}

public class ChildB : BaseClass<ChildB>
{
}

今静的MYPROPERTYはChildAとChildB

両方のためにユニークです
        ChildA TA = new ChildA();
        TA.MyProperty = 8;
        ChildB TB = new ChildB();
        TB.MyProperty = 4;

これは、あなたが求めているものとは少し異なりますが、おそらく同じことを実現します。

    class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine((new B()).theValue);
        Console.WriteLine((new C()).theValue);
        Console.ReadKey();
    }
}

public abstract class A
{
    public readonly string theValue;

    protected A(string s)
    {
        theValue = s;
    }
}

public class B : A
{
    public B(): base("Banana")
    {
    }
}

public class C : A
{
    public C(): base("Coconut")
    {
    }
}

やユースケースに応じて、あなたよりも良いではないかもしれないかもしれない別の解決策があります

abstract class ClassA
{
    private static class InternalClass<T> {
        public static string Value;
    }
    public string GetValue()
    {
        return (string)typeof(InternalClass<>)
              .MakeGenericType(GetType())
              .GetField("Value", BindingFlags.Public | BindingFlags.Static)
              .GetValue(null);
    }
}

このアプローチはEqualityComparer<T>.Defaultに使用されています。もちろん、この問題のために使用されていません。あなたは本当にGetValue抽象的にすることを検討し、各派生クラスでそれをオーバーライドする必要があります。

これは何でしょうか?



    class Base {
    protected static SomeObjectType myVariable;

    protected void doSomething()
    {
    Console.WriteLine( myVariable.SomeProperty );
    }
    }

    class AAA : Base
    {
    static AAA()
    {
    myVariable = new SomeObjectType();
    myVariable.SomeProperty = "A";
    }
    }

    class BBB : Base
    {
    static BBB()
    {
    myVariable = new SomeObjectType();
    myVariable.SomeProperty = "B";
    }
    }

これは私のために動作します。 インターフェイスでも、よりよいでしょう。

scroll top