C#继承-保存对最后一个实例的引用 [英] C# inheritance - save reference to last instance

查看:59
本文介绍了C#继承-保存对最后一个实例的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是提出了一个非常奇怪的问题,我无法弄清楚如何解决它.

I just came up with a really odd problem and I wasn't able to figure out how to solve it.

我有3个班级,班级A是班级B和班级C的基础,即:

I have 3 classes, the class A is the base for B and C, that is:

class A { ... }
class B : A { ... }
class C : B { ... }

现在,我想在这些类中具有一个静态属性,用于存储创建的每个类的最后一个对象,例如:

Now I would like to have a static property in these classes that stores the last object of each classes created, for example:

class A
{
    static public A lastInstance;
}

class B : A
{
    public B()
    {
        lastInstance = this;
    }
}

class C : A
{
    public C()
    {
        lastInstance = this;
    }
}

我想要实现的是能够为每个子类检索一个实例,例如:

What I would like to achieve is to be able to retrieve an instance for each subclass, for example:

var v1 = new B();
var v2 = new C();

var v3 = B.lastInstance;    // v3 == v1 and v3 != v2
var v4 = C.lastInstance;    // v4 == v2 and v4 != v3

有可能吗?

The only approach that seems promising to me shown in C# Static instance members for each inherited class: is it really the only chance I have to avoid defining a static member manually for each class?

推荐答案

我认为可以使用Dictionary完成,这是我现在唯一想到的方法:

I think this could be done with Dictionary and that's the only way i can think of right now:

class A {
    static Dictionary<Type, A> _LastInstances = new Dictionary<Type, A>(); // because every subclass will inherit from A
    public static A LastInstance {
        get {
            if ( _LastInstances.ContainsKey(GetType()) ) {
                return _LastInstances[GetType()];
            }
            return null;
        }

        protected set {
            if ( _LastInstances.ContainsKey(GetType()) ) {
                _LastInstances[GetType()] = value;
            } else {
                _LastInstances.Add(GetType(), value);
            }
        }
}

class B : A {
    public B(){
        LastInstance = this;
    }
}

这篇关于C#继承-保存对最后一个实例的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆