Create method with unlimited expression parameters?
I have created a repository method with the following signature:
T Get<TProperty>(int id, Expression<Func<T, TProperty>> include)
This works fine but I would like to extend it to take in an unlimited number of includes. I cannot simply use params because each include will return a different TProperty.
Is t开发者_如何学Gohere a nice way around this or do I have to create several overloads for 1, 2 or 3 includes for example?
If the TProperty types can be different, and if you want to make them different types, then you'd need several overloads.
T Get<TProperty>(int id, Expression<Func<T, TProperty>> include) { ... }
T Get<TProperty1, TProperty2>(int id, Expression<Func<T, TProperty1>> include1, Expression<Func<T, TProperty2>> include2)
OR you could use:
T Get(int id, params Expression<Func<T, object>>[] includes)
And rely on the covariance of the Func generic delegate, but then you'd have to handle the fact you're losing a bit of type safety.
Because Func is covariance on the return type, this means that if your delegate expects a return of object, you can still pass it a delegate with a narrower return type (though warning, with covariance value types aren't covariantly compatible with object, only reference types).
The code you have posted won't allow you to return a different TProperty but only the type you will specify at runtime as <TProperty>
You could use Params and use Object instead of the generic type
精彩评论