我正在尝试制作一个通用类。有没有办法进行约束,以便只有实现的对象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
如果我没记错的话,我知道该约束仅适用于类。这是可能的还是有人可以提供解决方法?