简体   繁体   English

在泛型类<T,U>的方法中比较两个T的变量(从C ++到C#的代码端口)

[英]Compare two vars of T in a method of a generic class<T,U> (code port from C++ to C#)

How to compare two vars of type T in a method of a generic class< T, U >? 如何在泛型类<T,U>的方法中比较两个类型为T的变量? Here is an example code which throws the following compiler error: 这是一个抛出以下编译器错误的示例代码:

Error CS0019 Operator '>=' cannot be applied to operands of type 'T' and 'T' 错误CS0019运算符'> ='不能应用于'T'和'T'类型的操作数

class IntervalSet< T, U >
{
    public void Add ( T start, T end, ref U val )
    {
        // new interval is empty?
        if (start >= end) // ERROR
            return; 
    }
}

I try to port source from C++ to C# and C# is new to me. 我尝试将源代码从C ++移植到C#,而C#对我来说是新的。 Thanks for your help. 谢谢你的帮助。

You must tell C# that T is comparable, otherwise you can only do System.Object things with T (and that's not much), excluding creating a new instance, since C# does not even know whether T has a default constructor: 你必须告诉C# T是可比较的,否则你只能用T做那个System.Object东西(那并不多),不包括创建一个新的实例,因为C#甚至不知道T是否有一个默认的构造函数:

class IntervalSet< T, U >
    where T : IComparable<T>
{
    public void Add ( T start, T end, ref U val )
    {
        if (start.CompareTo(end) >= 0) {
        }
    }
}

Note that standard types like int , string , DateTime etc. all implement this interface. 请注意, intstringDateTime等标准类型都实现了此接口。

See: IComparable<T> Interface , 请参阅: IComparable <T>接口
Constraints on Type Parameters (C# Programming Guide) 类型参数的约束(C#编程指南)

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

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