自定义 icomparer 错误 - 无法从用法中推断出类型参数

custom icomparer error - The type arguments cannot be inferred from the usage

我正在尝试将 IComparer 与泛型一起使用。

下面的代码会产生以下错误:"The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly."

如果我从 OrderBy 调用中删除自定义比较器,那么代码可以编译并正常排序,但是我需要能够传入我的 icomparer。 另外值得注意的是,如果我使用 object/string 等类型,下面的代码可以工作,但是当我尝试使用泛型类型

时,它会失败
public IQueryable<T> OrderResults<T, TU>(IQueryable<T> queryData, IComparer<TU> customComparer, string sortColumnName)
{
    var sortPropertyInfo = queryData.First().GetType().GetProperty(sortColumnName);
    return queryData.OrderBy(x => sortPropertyInfo.GetValue(x, null), customComparer);
}

由于 GetValue(x,null) returns 类型 System.Object,您的代码段存在一些歧义。请尝试以下操作:

public IQueryable<T> OrderResults<T, TU>(IQueryable<T> queryData, IComparer<TU> customComparer, string sortColumnName)
{
    var sortPropertyInfo = queryData.First().GetType().GetProperty(sortColumnName);
    return queryData.OrderBy(x => (TU)sortPropertyInfo.GetValue(x, null), customComparer);
}

这至少没有编译时错误。如果您有一些用于测试的代码,我可以验证它是否有效....