I have a method with declaration like this:
public void OriginalMethod(Func<object,bool> selector)
And I would like to call it from generic method, that has declaration like this:
public void GenericMethod<T>(Func<T, bool> selector)
How do I do that?
You can't pass the selector
directly to OriginalMethod
: it expects a method that accepts any object
, but a Func<T, bool>
accepts only an object of type T
.
Of course, you can cheat:
OriginalMethod(o => selector((T)o));
But if OriginalMethod
calls the method with an object that is not convertible to T, it will fail...
You need to create a Func<object, bool>
that calls the typed one passed in.
public void GenericMethod<T>(Func<T, bool> selector)
{
Func<object, bool> untypedSelector = (object obj) => selector((T)obj);
OriginalMethod(untypedSelector);
}
Either like the above, or a one-liner like Marc's answer .
OriginalMethod(arg => selector((T)arg));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.