简体   繁体   中英

Limiting generic types in C#

I have a generic class MyClass<T> where T should only be those types which can be compared.

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 .

where T : IComparable<T>

Interface documentation

This interface brings you the CompareTo method which is useful for relational ordering (greater than, less than, etc.). 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 . 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.)

You can limit the generic type to only classes that implement the IComparable interface using the where modifier.

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.

Maybe the next release of C# will have it, but I doubt...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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