Problem with a method that takes 2 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 as follows:

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 create a method that takes two lambdas and call it as I intended?

+3
source share
3 answers

Do SomePropertyu SomeOtherPropertyhave the same type? If not, this is your problem since you are using a single type parameter TResult.

The solution consists only in using two types of parameters:

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

Have you tried using 2 types of parameters?

For instance:

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

.

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
) 
0

Source: https://habr.com/ru/post/1752076/


All Articles