如果没有在子类中的任何代码,我想一个抽象类有一个静态变量的不同拷贝的每个子类。在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是为每个唯一的独特Ť 让导出两个子类,并且我们使用子类的名称如在基类中的通用吨。

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