泛型类型的二进制比较运算符运算符、类型

2023-09-04 23:54:24 作者:欲将沉醉换悲凉ペ

我有一个通用类,它接受一个类型 T 。在这一类我有一个方法是,我需要一个类型 T 来比较其他类型的 T 如:

I have a generic class that takes a type T. Within this class I have a method were I need to compare a type T to another type T such as:

public class MyClass<T>
{
    public T MaxValue
    {
        // Implimentation for MaxValue
    }

    public T MyMethod(T argument)
    {
        if(argument > this.MaxValue)
        {
             // Then do something
        }
    }
}

的MyMethod 的比较操作失败,编译器错误的 CS0019 。是否有可能约束添加到 T 来使这项工作?我尝试添加一个其中T:IComparable的&LT; T&GT; 类定义无济于事

The comparison operation inside of MyMethod fails with Compiler Error CS0019. Is it possible to add a constraint to T to make this work? I tried adding a where T: IComparable<T> to the class definition to no avail.

推荐答案

添加约束,以确保该类型实现 IComparable的&LT; T&GT; 是很长的路要走。但是,你不能使用&LT; 运营商 - 该接口提供了一个方法的CompareTo 做同样的事情:

Adding constraint to make sure that the type implements IComparable<T> is a way to go. However, you cannot use the < operator - the interface provides a method CompareTo to do the same thing:

public class MyClass<T> where T : IComparable<T> { 
    public T MaxValue  { 
        // Implimentation for MaxValue 
    } 

    public T MyMethod(T argument) { 
        if(argument.CompareTo(this.MaxValue) > 0){ 
             // Then do something 
        } 
    } 
}

如果你需要其他的数字运营商不仅仅是相比,情况是比较困难的,因为你不能添加约束,例如支持 + 运营商并没有相应的接口。这个can在这里找到。

If you needed other numeric operators than just comparison, the situation is more difficult, because you cannot add constraint to support for example + operator and there is no corresponding interface. Some ideas about this can be found here.

 
精彩推荐
图片推荐