建立一個泛型類型約束上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