如何确保数据类型实现IComparable接口

时间:2022-09-02 09:12:26

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 而不是IComparable - 它可以让生活变得更轻松(并避免一些拳击,但这不是一个问题)。最后,请记住,如果要对类似的位进行鸭式输入(如List .Sort()的工作原理),可以在代码中使用Comparer .Default和Comparer.Default。

#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 .Default。根据我的理解,它首先获得IComparable ,如果它找不到它然后它获得IComparable版本,否则它会引发异常。

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 而不是IComparable - 它可以让生活变得更轻松(并避免一些拳击,但这不是一个问题)。最后,请记住,如果要对类似的位进行鸭式输入(如List .Sort()的工作原理),可以在代码中使用Comparer .Default和Comparer.Default。

#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 .Default。根据我的理解,它首先获得IComparable ,如果它找不到它然后它获得IComparable版本,否则它会引发异常。

double s = 5;
double t = 10;
int result = Comparer<double>.Default.Compare(s, t);