有基类的静态成员的单独的副本中每个派生类 [英] Having separate copy of base class static member in each derived class

查看:124
本文介绍了有基类的静态成员的单独的副本中每个派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类的结构:

public abstract class PresenterBase
{
    public static Dictionary<string, MethodInfo> methodsList;

    public void Bind()
    public void Initialize();
}


public class DevicePresenter: PresenterBase
{
   public void ShowScreen();
   public void HandleEvents();    
}

public class HomePresenter: PresenterBase
{
   public void ShowScreen();
   public void HandleEvents();
}

我想有家庭presenter和设备presenter有在presenterBase定义methodsList静态成员的单独副本。

I want to have HomePresenter and DevicePresenter to have separate copy of methodsList static member defined in PresenterBase.

不幸的是,他们与上面的实现共享相同的副本。

Unfortunately they share the same copy with above implementation.

时,他们另一种方法,我可以有methodsList的独立副本首页$ ​​P $ psenter和设备presenter? 我不甘心定义methodsList在派生类中,因为在未来,如果有人增加了一个派生类中,他将不得不牢记methodsList添加到该级。

Is they alternative approach, that I can have separate copy of methodsList for HomePresenter and DevicePresenter? I am not willing to define methodsList in derived classes because in future if someone adds another derived class he will have to keep in mind to add methodsList to that class.

推荐答案

不要让静态的。不就是工作吗?

Don't make it static at all. Won't that work?

静态与类型相关联的手段;非 - 静态与实例相关联的手段

static means associated with the type; non-static means associated with the instance.

我没有一个Visual Studio实例得心应手,但我相信你也标志着基类中的字段摘要;那么编译器会要求你将它添加到任何派生类。你绝对可以做到这一点的一个属性。

I don't have a Visual Studio instance handy, but I believe you could also mark the field abstract in the base class; then the compiler will require you to add it to any deriving classes. You can definitely do that with a property.

在另一方面,鉴于上述code,我可能会添加抽象方法 ShowScreen() HandleEvents() presenterBase

On another note, given the above code, I would probably add abstract methods ShowScreen() and HandleEvents() to PresenterBase.

这篇关于有基类的静态成员的单独的副本中每个派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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