Problem with a method that accepts 2 lambdas
I have the following class:
public class MyClass<T> where T : class
{
public void Method1<TResult>(T obj, Expression<Func<T, TResult>> expression)
{
//Do some work here...
}
public void Method2<TResult>(T obj, Expression<Func<T, TResult>> expression1, Expression<Func<T, TResult>> expression2)
{
//Do some work here...
}
}
I can call Method1 like this:
MyClass<SomeOtherClass> myObject = new MyClass<SomeOtherClass>();
myObject.Method1(someObject, x => x.SomeProperty);
But when I try to call Method2:
MyClass<SomeOtherClass> myObject = new MyClass<SomeOtherClass>();
myObject.Method2(someObject, x => x.SomeProperty, x => x.SomeOtherProperty);
I get the following compile-time error:
Error 1 The type arguments for method 'MyClass.Method2<SomeOtherClass>.Method2<TResult>(SomeOtherClass obj, System.开发者_如何学CLinq.Expressions.Expression<System.Func<SomeOtherClass,TResult>>, System.Linq.Expressions.Expression<System.Func<SomeOtherClass,TResult>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
How can I make an method that accept two lambdas and call it like I intended?
Do SomeProperty
and SomeOtherProperty
have the same type? If not, there's your problem, since you're using one TResult
type parameter.
The solution is just to use two type parameters:
public void Method2<TResult1, TResult2>(T obj, Expression<Func<T, TResult1>> expression1, Expression<Func<T, TResult2>> expression2)
{
//Do some work here...
}
Have you tried using 2 type parameters instead?
Eg:
void Method2<TResult1, TResult2>(T obj,
Expression<Func<T, TResult1>> expression1,
Expression<Func<T, TResult2>> expression2)
You could try specifying the type argument explicity.
myObject.Method2<string>(
someObject,
x => x.SomeProperty,
x => x.SomeOtherProperty);
If that doesn't work (say SomeProperty and SomeOtherProperty are different types) you could allow for additional type information in the method declaration.
public void Method2<TResult1, TResult2>
(
T obj,
Expression<Func<T, TResult1>> expression1,
Expression<Func<T, TResult2>> expression2
)
精彩评论