슈퍼 클래스를 만드는 것은 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()];
    }
    ...
}

이것이 잘 작동하지만 더 우아하거나 내장 된 방법이 있는지 궁금합니다.

이것은 비슷합니다 각기 다른 유형의 상속 클래스마다 정적 변수의 다른 사본을 가질 수 있습니까?, 그러나 나는 서브 클래스를 제어 할 수 없다

도움이 되었습니까?

해결책

이것이 잘 작동하지만 더 우아하거나 내장 된 방법이 있는지 궁금합니다.

여기서 기본적인 OO 원칙을 위반하기 때문에 실제로이 작업을 수행하는 방법은 없습니다. 기본 클래스는 전통적인 객체 지향 이론에서 서브 클래스에 대한 지식이 없어야합니다.

즉,이 작업을 수행해야한다면 구현은 아마도 하위 클래스에 직접 다른 정보를 추가 할 수 없다면 얻을만큼 좋은 것일 수 있습니다. 이것을 제어해야하고 서브 클래스를 변경할 수 없다면 이것이 최선의 접근법 일 것입니다.

다른 팁

더 우아한 방법이 있습니다. 일반 기본 클래스의 정적이 다른 유형의 파생 클래스마다 다르다는 사실을 악용 할 수 있습니다.

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에 대해 고유하며 두 개의 아동 수업을 도출하고 기본 클래스의 일반 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";
    }
    }

그것은 나를 위해 작동합니다. 인터페이스가 더 좋을 것입니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top