简体   繁体   English

限制C#中的泛型类型

[英]Limiting generic types in C#

I have a generic class MyClass<T> where T should only be those types which can be compared. 我有一个泛型类MyClass<T> ,其中T应该只是那些可以比较的类型。

This would mean only numeric types and classes where methods for the relational operators have been defined. 这将仅表示已定义关系运算符的方法的数字类型和类。 How do I do this ? 我该怎么做呢 ?

You cannot constrain to operators, but you can constrain to interfaces. 您不能限制运算符,但可以约束接口。 Therefore, intending to use >=, <=, == is out, but you could use CompareTo, Equals . 因此,打算使用>=, <=, == ,但你可以使用CompareTo, Equals

where T : IComparable<T>

Interface documentation 界面文档

This interface brings you the CompareTo method which is useful for relational ordering (greater than, less than, etc.). 此接口为您提供CompareTo方法,该方法对于关系排序(大于,小于等)非常有用。 Primitives and strings implement this already, but you would need to implement this for your own custom types. 基元和字符串已实现此功能,但您需要为自己的自定义类型实现此功能。 You would use it like this 你会像这样使用它

void SomeMethod<T>(T alpha, T beta) where T : IComparable<T>
{
    if (alpha.CompareTo(beta) > 0) 
    {
        // alpha is greater than beta, replaces alpha > beta
    }
    else if (alpha.CompareTo(beta) < 0)
    {
        // alpha is less than beta, replaces alpha < beta
    }
    else 
    {
        // CompareTo returns 0, alpha equals beta
    }
}

Equals you get by default as a virtual method on object . 默认情况下,您将获得Equals object虚拟方法。 You want to override this method on your own custom types if you want something other than referential equality to be used. 如果要使用除引用相等之外的其他内容,则希望在自己的自定义类型上覆盖此方法。 (It is also strongly recommended to override GetHashCode at the same time.) (强烈建议同时覆盖GetHashCode 。)

You can limit the generic type to only classes that implement the IComparable interface using the where modifier. 您可以将泛型类型限制为仅使用where修饰符实现IComparable接口的类。

public class MyClass<K> where K : IComparable
{
  ....
}

如果您想将其限制为可以比较的内容,您可以执行以下操作:

public class MyClass<T> where T:IComparable

If speed is of relevance using the suggested methods will give you a tremendous loss in performance. 如果速度与使用建议的方法相关将会给您带来巨大的性能损失。 If not, all the suggested things work fine. 如果没有,所有建议的事情都可以正常工作。

This is an issue I have to address very often since the primitive datatypes in C# do not have an "Numeric" datatype as often suggested and demanded by others here. 这是我必须经常解决的问题,因为C#中的原始数据类型没有像其他人经常建议和要求的“数字”数据类型。

Maybe the next release of C# will have it, but I doubt... 也许C#的下一个版本会有它,但我怀疑......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM