I had the following code:
protected void Initialize(){
thi开发者_如何学Gos.Fonts.Initialize();
this.Screens.Initialize();
this.Menu.Initialize();
}
protected void Update(){
this.Screens.Update();
this.Menu.Update();
}
After writing this, I re-factored the code to:
protected void Initialize(){
this.CallMethod<INeedInitialization>(
(i) => { i.Initialize(); }
, this.Fonts, this.Screens, this.Menu
);
}
protected void Update(){
this.CallMethod<INeedUpdating>(
(i) => { i.Update(); }
, this.Screens, this.Menu
);
}
private void CallMethod<T>(Action<T> action, params T[] items){
items.ToList().ForEach(i => action(i));
}
Then, I realized that in my code base, there is a lot of reuse of the CallMethod<T>
type of operations, so I futher re-factored to:
public static extensions{
// I use object type as I can have INeedInitialization, INeedUpdate etc...
public static void CallMethod<T>(this object obj, Action<T> action,
params T[] items){
items.ToList().ForEach(i => action(i));
}
}
Now, I can get the CallMethod<T>
on all my objects, but somehow after doing this, I feel there is something fundamentally wrong with this code & not able to pin-point why I feel it not being correct.
In addition - how can I put OR constraints on the generic method to accept only INeedUpdating
or INeedInitialize
type of objects only instead of extending the base Object
type?
Can someone please help?
Thanks!
KISS principle!
This seems to be to an example of Fancy Coding Syndrome. I see nothing gained from the general routines and a significant expense in extra code to maintain, debug and test through.
To answer your question, you can create two copies of the function, one for each interface:
public static void CallMethod<T>(this INeedUpdating obj, Action<T> action,
params T[] items){
items.ToList().ForEach(i => action(i));
}
public static void CallMethod<T>(this INeedInitialize obj, Action<T> action,
params T[] items){
items.ToList().ForEach(i => action(i));
}
But I have to wonder if your tangled mess is really more readable than simply saying:
foreach(var item in new INeedInitialization[]{this.Fonts, this.Screens, this.Menu})
item.Initialize();
Yeah, it looks weird. The first thing that came to me was to create collections of theese and then simply loop them in the method.
List<INeedInitialization> InitializedComponents = new List<INeedInitialization> {Fonts, Screens, Menus};
List<INeedUpdating> UpdatedComponents = new List<INeedUpdating> {Screens, Menus}
protected void Initialize(){
foreach(var i in InitializedComponents)
i.Initialize();
}
protected void Update(){
foreach(var u in UpdatedComponents)
u.Update();
}
And this can nicely be part of complex class hiearchy by simply adding more items into collections without changing or overriding the methods themselves.
精彩评论