Question about c # encoding

I had the following code:

protected void Initialize(){
  this.Fonts.Initialize();
  this.Screens.Initialize();
  this.Menu.Initialize();
}

protected void Update(){
  this.Screens.Update();
  this.Menu.Update();
}

After writing this, I re-memorized the code:

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 there is a lot of reuse of type operations in my code base CallMethod<T>, so I will repeat factorization:

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 CallMethod<T>on all my objects, but somehow after that I feel that there is something fundamentally wrong in this code, and I can’t say why I think that this is not right.

Also, how can I put OR constraints on a generic method to accept only object types INeedUpdatingor INeedInitialize, rather than extending the base type Object?

Can anybody help?

Thank!

+3
source share
3 answers

KISS!

Fancy Coding. , .

+4

, : :

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

, , :

foreach(var item in new INeedInitialization[]{this.Fonts, this.Screens, this.Menu})
    item.Initialize();
0

Yes, that looks weird. The first thing that came to me was the creation of thees collections, and then just their cycle 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 be part of the complex hiearchy class by simply adding more elements to the collection without changing or overriding the methods themselves.

0
source

All Articles