I need to make sure that a datatype implements the IComparable interface, and I was wondering if there was anyway to make that a requirement when you create the object?
我需要确保一个数据类型实现IComparable接口,我想知道在创建对象时是否还有一个要求?
3 个解决方案
#1
You can perhaps use generic to do this, for example:
您也许可以使用泛型来执行此操作,例如:
public static T Create<T>() where T : IComparable<T>, new() {
return new T();
}
Or if you mean "when you create the type" (in code), then no; you'd just have to remember, perhaps using unit-tests to verify that you've done it.
或者如果你的意思是“当你创建类型”(在代码中),那么没有;你只需要记住,也许使用单元测试来验证你已经完成它。
I recommend using the typed IComparable<T>
over IComparable
- it makes life a lot easier (and avoids some boxing, but that is less of an issue). Finally, remember that you can use Comparer<T>.Default
and Comparer.Default
in code if you want to duck-type the comparable bit (like how List<T>.Sort()
works).
我建议使用类型IComparable
#2
For a generic class you can do:
对于泛型类,您可以执行以下操作:
public class MyType<T>
where T:IComparable<T>
#3
You also might want to look into Comparer<T>.Default. From what I understand it gets the IComparable<T> first, if it can't find that then it gets the IComparable version, otherwise it throws an exception.
您还可能需要查看Comparer
double s = 5;
double t = 10;
int result = Comparer<double>.Default.Compare(s, t);
#1
You can perhaps use generic to do this, for example:
您也许可以使用泛型来执行此操作,例如:
public static T Create<T>() where T : IComparable<T>, new() {
return new T();
}
Or if you mean "when you create the type" (in code), then no; you'd just have to remember, perhaps using unit-tests to verify that you've done it.
或者如果你的意思是“当你创建类型”(在代码中),那么没有;你只需要记住,也许使用单元测试来验证你已经完成它。
I recommend using the typed IComparable<T>
over IComparable
- it makes life a lot easier (and avoids some boxing, but that is less of an issue). Finally, remember that you can use Comparer<T>.Default
and Comparer.Default
in code if you want to duck-type the comparable bit (like how List<T>.Sort()
works).
我建议使用类型IComparable
#2
For a generic class you can do:
对于泛型类,您可以执行以下操作:
public class MyType<T>
where T:IComparable<T>
#3
You also might want to look into Comparer<T>.Default. From what I understand it gets the IComparable<T> first, if it can't find that then it gets the IComparable version, otherwise it throws an exception.
您还可能需要查看Comparer
double s = 5;
double t = 10;
int result = Comparer<double>.Default.Compare(s, t);