【发布时间】:2010-06-28 13:06:35
【问题描述】:
我有以下课程:
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.
如何创建一个接受两个 lambda 表达式并按照我的意图调用它的方法?
【问题讨论】:
-
x.SomeProperty 和 x => x.SomeOtherProperty 是否属于同一类型?