建立一个泛型类型约束上T.
public class BindingProperty<T> : IComparable where T : IComparable
{
public T Value {get; set;}
public int CompareTo(object obj)
{
if (obj == null) return 1;
var other = obj as BindingProperty<T>;
if (other != null)
return Value.CompareTo(other.Value);
else
throw new ArgumentException("Object is not a BindingProperty<T>");
}
}
编辑:
替代解决方案来处理,如果值不落实IComparable
。这将支持所有类型,只是如果它们不执行IComparable
就不会进行排序。
public class BindingProperty<T> : IComparable
{
public T Value {get; set;}
public int CompareTo(object obj)
{
if (obj == null) return 1;
var other = obj as BindingProperty<T>;
if (other != null)
{
var other2 = other as IComparable;
if(other2 != null)
return other2.CompareTo(Value);
else
return 1; //Does not implement IComparable, always return 1
}
else
throw new ArgumentException("Object is not a BindingProperty<T>");
}
}
什么是泛型列表的类型? – twilson 2012-02-11 12:41:33
IList已用于绑定DataGrid列。 – 2012-02-11 13:34:21