接受 2 个 lambda 的方法存在问题
我有以下类:
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 并按我的预期调用它的方法?
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.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.
How can I make an method that accept two lambdas and call it like I intended?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
SomeProperty
和SomeOtherProperty
是否具有相同的类型?如果没有,那就是你的问题,因为你使用的是一个TResult
类型参数。解决方案只是使用两个类型参数:
Do
SomeProperty
andSomeOtherProperty
have the same type? If not, there's your problem, since you're using oneTResult
type parameter.The solution is just to use two type parameters:
您是否尝试过使用 2 个类型参数?
例如:
Have you tried using 2 type parameters instead?
Eg:
您可以尝试明确指定类型参数。
如果这不起作用(假设 SomeProperty 和 SomeOtherProperty 是不同的类型),您可以在方法声明中允许附加类型信息。
You could try specifying the type argument explicity.
If that doesn't work (say SomeProperty and SomeOtherProperty are different types) you could allow for additional type information in the method declaration.