我試圖做一個泛型類。有沒有辦法制定一個約束,以便只有實現了IComparable
的對象才能被傳遞到我的泛型中。例如:將泛型類綁定到特定的接口
public class MyClass<T>
{
}
public class MyFooClass
{
}
public class MyComparableFooClass : IComparable
{
public int Compare(MyComparableFooClass q)
{
return 0;
}
}
public class MyMainClass()
{
private MyClass<int> _myIntClass; // This is okay since int implements IComparable
private MyClass<MyComparableFooClass> _myComparableFooClass // This should be okay too since int implements IComparable
private MyClass<MyFooClass> _myFooClass; // This should get a compile error since MyFooClass doesn't implement IComparable
}
希望我的例子很清楚。我只想MyClass<T>
允許實現IComparable
的對象。我知道where
約束只適用於類,如果我沒有弄錯的話。這是可能的還是可以有人提供解決方法?