Having separate copy of base class static member in each derived class

感情迁移 提交于 2019-12-07 10:04:04

问题


I have following class structure:

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();
}

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.

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.


回答1:


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

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

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.

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




回答2:


To answer the question directly, you could make the base class generic, this will give you seperate static dictionaries, if this is a good design or not is another question.

public abstract class PresenterBase<T> where T : PresenterBase<T>
{
    public static Dictionary<string, MethodInfo> methodsList = 
         new Dictionary<string,MethodInfo>();

}

public class DevicePresenter : PresenterBase<DevicePresenter>
{

}

public class HomePresenter : PresenterBase<HomePresenter>
{

} 



回答3:


I would not make it static, as you want each instance to have its own list, define methodsList as a property of PresenterBase and define a constructor in PresenterBase which takes the Dictionary<string, MethodInfo> and sets the propety to this value

That way you ensure that any derived class must provide this, but each instance has its own list.

I would also define abstract methods ShowScreen() and HandleEvents() to the PresenterBase as @Michael Kjorling suggests



来源:https://stackoverflow.com/questions/5337038/having-separate-copy-of-base-class-static-member-in-each-derived-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!