I have the following code
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
}
Which needs to cast a System.Func<T, TKey>
to System.Func<T, IComparable>
Why does
SortTerm<Db.T_projects>.Create(x => x.name);
work, while
SortTerm<Db.T_projects>.Create(x => x.id);
gives an Invalid Cast
InvalidCastException: Unable to cast object of type 'System.Func2[Db.T_projects,System.Int64]' to type 'System.Func2[Db.T_projects,System.IComparable]'.
when long/Int64 is defined as
public struct Int64 : IComparable, IComparable<Int64>, IConvertible, IEquatable<Int64>, IFormattable
While string is defined no differntly as IComparable...
public sealed class String : IEnumerable<char>, IEnumerable, IComparable, IComparable<String>, IConvertible, IEquatable<String>, ICloneable
for completeness
public partial class T_projects
{
public long id; // int not null
public string name; // nvarchar(4000) not null
}
Shouldn't this work ?
And more importantly, how to make this work ?
Note:
There is gonna be a List<SortTerm<T>>,
so I can't just use TKey in the sort-definition.