如何解决这个错误不能从用法中推断出来.尝试显式指定类型参数
本文关键字:推断出 类型参数 用法 解决 何解决 不能 错误 | 更新日期: 2023-09-27 18:06:30
static Func<T, object> CreateSelector<T>(IEnumerable<string> propertyNames)
{
var sourceType = typeof(T);
var parameter = Expression.Parameter(sourceType, "e");
var properties = propertyNames.Select(name => Expression.PropertyOrField(parameter, name)).ToArray();
var selector = Expression.Lambda<Func<T, object>>(
Expression.Call(typeof(Tuple), "Create", properties.Select(p => p.Type).ToArray(), properties),
parameter);
return selector.Compile();
}
public static IEnumerable<Tuple<T, T>> Join<T>(this IEnumerable<T> left, IEnumerable<T> right, IEnumerable<string> propertyNames)
{
var keySelector = CreateSelector<T>(propertyNames);
return left.Join(right, keySelector, keySelector, Tuple.Create);
}
public static bool CompareLists<T1, T2>(IEnumerable<T1> lstProduct1, IEnumerable<T2> lstProduct2, List<DuplicateExpression> DuplicateExpression)
{
string[] Fields = DuplicateExpression.Select(x => x.ExpressionName).ToArray();
var JoinExp = lstProduct1.Join(lstProduct2, Fields);
bool IsSuccess = true;// CompareTwoLists(lstProduct1, lstProduct2, (listProductx1, listProductx2) => JoinExp.Any());
return IsSuccess;
}
当我编译上面的代码;
下面的行出现错误var JoinExp = lstProduct1.Join(lstProduct2, Fields);
错误错误1方法的类型参数"AP.Classes.ListComparison.Join (System.Collections.Generic.IEnumerable,System.Collections.Generic.IEnumerable,System.Collections.Generic.IEnumerable)'不能被推断从用法来看。尝试指定类型参数明确。D: '车间'美联社'类' DuplicateValidator.cs
如何解决这个错误?我正在创建一个列表比较工具
提供的自定义Join
方法不适用,因为它期望一个泛型类型参数,而您的方法有两个。
您可以使用提供的CreateSelector
实现来实现自定义Join
/GroupJoin
扩展方法,类似于Enumerable
类中相应的系统提供的方法,如下所示:
public static IEnumerable<TResult> Join<TOuter, TInner, TResult>(this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, IEnumerable<string> propertyNames, Func<TOuter, TInner, TResult> resultSelector)
{
return outer.Join(inner, CreateSelector<TOuter>(propertyNames), CreateSelector<TInner>(propertyNames), resultSelector);
}
public static IEnumerable<TResult> GroupJoin<TOuter, TInner, TResult>(this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, IEnumerable<string> propertyNames, Func<TOuter, IEnumerable<TInner>, TResult> resultSelector)
{
return outer.GroupJoin(inner, CreateSelector<TOuter>(propertyNames), CreateSelector<TInner>(propertyNames), resultSelector);
}
然后你可以使用上面的自定义GroupJoin
来有效地实现你的方法:
public static bool CompareLists<T1, T2>(IEnumerable<T1> list1, IEnumerable<T2> list2, List<DuplicateExpression> DuplicateExpression)
{
var fields = DuplicateExpression.Select(x => x.ExpressionName).ToArray();
return list1.GroupJoin(list2, fields, (x, match) => match).All(match => match.Any())
&& list2.GroupJoin(list1, fields, (x, match) => match).All(match => match.Any());
}