开发者

Limiting generic types in C#

开发者 https://www.devze.com 2023-03-25 09:58 出处:网络
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 d

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
{
  ....
}


If you want to limit it to things that can be compared, you can do things like:

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...

0

精彩评论

暂无评论...
验证码 换一张
取 消