Generic lookup function as parameter
I'm trying to clean duplicate code. The only difference are calls l开发者_运维百科ike
MyType x = Foo.LookupService<MyType>();
vs.
MyType x = Bar.FindService<MyType>();
So we have two methods of type T xxx<T>()
, i.e. a method returning an instance of T
given the class parameter T
. How could I pass such functions as a parameter to a method that tries to find instances of different types, something like
foo([magic generics stuff] resolve)
{
MyType x = resolve<MyType>();
MyOtherType y = resolve<MyOtherType>();
}
In response to your updated question, I'd have to say it looks like what you'll need to do is accept a parameter that implements an interface--something like IResolver
, perhaps--which in turn provides a generic Resolve<T>
method:
public interface IResolver
{
T Resolve<T>();
}
void foo(IResolver resolver)
{
MyType x = resolver.Resolve<MyType>();
MyOtherType y = resolver.Resolve<MyOtherType>();
}
The reason for this is that you cannot (as far as I know) pass a generic delegate as a parameter to a non-generic method. What I mean is, you cannot have this:
void foo(Func<T> resolve)
{
}
When T
is a type parameter, it has to be established within the declaration, not within the parameters themselves. Hopefully that makes sense.
[magic generics stuff]
= Func<TResult>
精彩评论