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

I have the 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 HomePresenter and DevicePresenter to have a separate copy of the staticList of the static member defined in PresenterBase.

Unfortunately, they use the same copy with the above implementation.

Are they an alternative approach that I can have a separate copy of the List methods for HomePresenter and DevicePresenter? I do not want to define the List methods in derived classes, because in the future, if someone adds another derived class, he will have to keep in mind adding the List methods to this class.

+4
source share
3 answers

Do not put it at all. Will not work?

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

I do not have an instance of Visual Studio, but I believe that you can also mark the abstract field in the base class; then the compiler will require you to add it to any receiver classes. You can definitely do this with a property.

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

+6
source

To answer the question directly, you can make the base class general, it will give you separate static dictionaries, if it is a good design or not, this 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
source

I would not become static, since each instance should have its own list, define the List methods as a PresenterBase property and define a constructor in PresenterBase that takes a Dictionary<string, MethodInfo> and sets the propety value for this value

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

I would also define the abstract ShowScreen() and HandleEvents() methods in PresenterBase , as @Michael Kjorling offers

+1
source

Source: https://habr.com/ru/post/1344068/


All Articles