Binding a generic class to a specific interface
-
07-07-2021 - |
题
I am trying to make a generic class. Is there a way to make a constraint so that only objects that implement IComparable
can be passed into my generic. For example:
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
}
Hopefully my example is clear. I just want MyClass<T>
to allow objects that implement IComparable
. I understand that the where
constraint only works with classes, if I'm not mistaken. Is this possible or can someone offer a work around?
解决方案
Generic constraint's work with interfaces too. From the documentation
where T : class The type argument must be a reference type, including any class, interface, delegate, or array type.
So you can use the keyword where
with IComparable
:
public class MyClass<T> where T : IComparable
{
}
其他提示
Generic does work with interface also:
public class MyClass<T> where T: IComparable
{
}
不隶属于 StackOverflow