【问题标题】:Problem with a method that accepts 2 lambdas接受 2 个 lambda 的方法存在问题
【发布时间】: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 是否属于同一类型?

标签: c# linq generics lambda


【解决方案1】:

SomePropertySomeOtherProperty 是否具有相同的类型?如果没有,那就是你的问题,因为你使用了一个 TResult 类型参数。

解决方法就是使用两个类型参数:

public void Method2<TResult1, TResult2>(T obj, Expression<Func<T, TResult1>> expression1, Expression<Func<T, TResult2>> expression2)
{
    //Do some work here...
}

【讨论】:

    【解决方案2】:

    您是否尝试过使用 2 个类型参数来代替?

    例如:

    void Method2<TResult1, TResult2>(T obj, 
       Expression<Func<T, TResult1>> expression1, 
       Expression<Func<T, TResult2>> expression2)
    

    【讨论】:

      【解决方案3】:

      您可以尝试明确指定类型参数。

      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
      ) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多