在 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>");
}
}