我有以下课程:
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...
}
}
我可以像这样调用Method1:
MyClass<SomeOtherClass> myObject = new MyClass<SomeOtherClass>();
myObject.Method1(someObject, x => x.SomeProperty);
但是当我尝试调用Method2时:
MyClass<SomeOtherClass> myObject = new MyClass<SomeOtherClass>();
myObject.Method2(someObject, x => x.SomeProperty, x => x.SomeOtherProperty);
我收到以下编译时错误:
Error 1 The type arguments for method 'MyClass.Method2<SomeOtherClass>.Method2<TResult>(SomeOtherClass obj, System.Linq.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.
如何创建一个接受两个lambdas的方法,并按照我的意图调用它?
答案 0 :(得分:7)
SomeProperty
和SomeOtherProperty
具有相同的类型吗?如果没有,那就是你的问题,因为你使用了一个TResult
类型参数。
解决方案只是使用两个类型参数:
public void Method2<TResult1, TResult2>(T obj, Expression<Func<T, TResult1>> expression1, Expression<Func<T, TResult2>> expression2)
{
//Do some work here...
}
答案 1 :(得分:4)
您是否尝试过使用2种类型参数?
例如:
void Method2<TResult1, TResult2>(T obj,
Expression<Func<T, TResult1>> expression1,
Expression<Func<T, TResult2>> expression2)
答案 2 :(得分:0)
您可以尝试指定类型参数explicity。
myObject.Method2<string>(
someObject,
x => x.SomeProperty,
x => x.SomeOtherProperty);
如果这不起作用(比如SomeProperty和SomeOtherProperty是不同的类型),您可以在方法声明中允许其他类型信息。
public void Method2<TResult1, TResult2>
(
T obj,
Expression<Func<T, TResult1>> expression1,
Expression<Func<T, TResult2>> expression2
)