我有以下代码。
为了完整性。
public class SortTerm<T>
{
public System.Func<T, System.IComparable> Sort;
public SortDirection Direction;
public SortTerm(System.Func<T, System.IComparable> sorter, SortDirection direction)
{
this.Sort = sorter;
this.Direction = direction;
}
public SortTerm(System.Func<T, System.IComparable> sorter)
: this(sorter, SortDirection.Ascending)
{ }
public static SortTerm<T> Create<TKey>(System.Func<T, TKey> sorter, SortDirection direction)
where TKey : System.IComparable
{
return new SortTerm<T>((System.Func<T, System.IComparable>)(object)sorter, direction);
} // End Constructor
public static SortTerm<T> Create<TKey>(System.Func<T, TKey> sorter)
where TKey : System.IComparable
{
return Create<TKey>(sorter, SortDirection.Ascending);
} // End Constructor
}
需要将 System.Func<T, TKey>
转换为 System.Func<T, IComparable>
为什么要这样做呢?
SortTerm<Db.T_projects>.Create(x => x.name);
工作,同时
SortTerm<Db.T_projects>.Create(x => x.id);
出现"无效转换"错误
InvalidCastException: 无法将类型为'System.Func2[Db.T_projects,System.Int64]'的对象转换为类型'System.Func2[Db.T_projects,System.IComparable]'。
当long/Int64被定义为
public struct Int64 : IComparable, IComparable<Int64>, IConvertible, IEquatable<Int64>, IFormattable
虽然字符串与IComparable没有任何不同...
public sealed class String : IEnumerable<char>, IEnumerable, IComparable, IComparable<String>, IConvertible, IEquatable<String>, ICloneable
为了完整性。
public partial class T_projects
{
public long id; // int not null
public string name; // nvarchar(4000) not null
}
这个应该可以工作吧?
更重要的是,如何让它工作?
注意:
会有一个List<SortTerm<T>>
,所以我不能在排序定义中仅使用TKey。
Int64
)不受支持。string
是引用类型,所以可以使用。 - René Vogt