代码之家  ›  专栏  ›  技术社区  ›  Raphael

接受2个lambda的方法有问题

  •  3
  • Raphael  · 技术社区  · 15 年前

        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并按预期调用的方法?

    3 回复  |  直到 15 年前
        1
  •  7
  •   Dan Tao    15 年前

    SomeProperty SomeOtherProperty 有相同类型的吗?如果没有,那就是你的问题了,因为你在用 TResult

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

    public void Method2<TResult1, TResult2>(T obj, Expression<Func<T, TResult1>> expression1, Expression<Func<T, TResult2>> expression2)
    {
        //Do some work here...
    }
    
        2
  •  4
  •   leppie    15 年前

    你试过使用2个类型参数吗?

    void Method2<TResult1, TResult2>(T obj, 
       Expression<Func<T, TResult1>> expression1, 
       Expression<Func<T, TResult2>> expression2)
    
        3
  •  0
  •   Amy B    15 年前

    您可以尝试显式地指定类型参数。

    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
    )