简体   繁体   中英

Generic method with property expression “type arguments cannot be inferred from useage”

I hope I'm not having a meltdown here - will happily delete this question if I am... but given the following method:

IList<T> ConvertSomething<T, TProperty>(IList<T> original, Expression<Func<T, TProperty>> valuePropertyExpression, Expression<Func<T, TProperty>> namePropertyExpression);

..I can call it like this:

var data = new List<MyType>(); // would be real data of that type
var output = _factory.ConvertSomething<MyType, object>(data, x => x.Id, x => x.Name);

..but not like this:

var output = _factory.ConvertSomething(data, x => x.Id, x => x.Name);

The second version causes the compiler to complain, with the "cannot be inferred from useage" error.

So my questions are:

  1. is what I am doing possible when only the method can know about T
  2. if not, is there another approach (I need to know the two requested PropertyInfo objects to do my 'conversion' and don't want the user to have to do it by string).

That is because the type of Id and Name are different. since object is compatible with both of them you are able to call it specifying object. You can add a third generic argument like this:

IList<T> ConvertSomething<T, TValue, TName>(
     IList<T> original, 
     Expression<Func<T, TValue>> valuePropertyExpression, 
     Expression<Func<T, TName>> namePropertyExpression);

Then the types should be inferred correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM