Generic method calling duplication
I have the following code:
switch (objectType)
{
case ObjectType.UserReview:
return MyMethod<UserReview>();
case ObjectType.ProfessionalReview:
return MyMethod<ProfessionalReview>();
case ObjectType.Question:
return MyMethod<Question>();
case ObjectType.News:
return MyMethod<News>();
default:
throw new ArgumentOutOfRangeException("objectType开发者_开发知识库");
}
Now I need the same code but for calling another method. Are there any options to implement it without duplication and Reflection?
Sounds like an ideal opportunity to replace conditional with polymorphism. Can you promote ObjectType.UserReview
to be a class (it looks like an enum
at the moment) and put the switch block as a polymorphic method?
You can let MyMethod
take an interface as an argument, e.g. IObjectType
, like this:
MyMethod(IObjectType objectType)
That interface should contain the necessary and common method(s) that MyMethod will call, in your case:
interface ObjectType
{
string GetQuery();
}
Then let each ObjectType implement that interface with it's own specific CreateObjectSet<T>.Where(...)
, i.e. UserReview
, ProfessionalReview
and so on.
You then call MyMethod
like this:
MyMethod(new UserReview()) // Ok because UserReview implements IObjectType
Finally it's simply a matter of letting MyMethod
call objectType.DoWork()
.
You could pass in delegates.
As far as I know, you can't partially resolve a generic delegate to a supplied method, with the generic type derived case by case, so that would mean 4 function references would need to be passed in.
public static string DoStuff<T,U,V,W>(Type objectType,
Action<T> f, Action<U> g, Action<V> h, Action<W> i)
{
switch (objectType)
{
case ObjectType.UserReview:
return f();
case ObjectType.ProfessionalReview:
return g();
case ObjectType.Question:
return h();
case ObjectType.News:
return i();
default:
throw new ArgumentOutOfRangeException("objectType");
}
}
精彩评论