如何比较泛型方法中的两个值?

Box*_*Box 1 c# generics comparison

我需要创建泛型方法,返回两个参数中的更多.运营商>和<不起作用.这是我方法的签名:

public static T Greater<T>(ref T a, ref T b)
{
    if (a > b) 
    {
       return a;
    }
    else 
    {
       return b;
    }
}
Run Code Online (Sandbox Code Playgroud)

我是C#中的新手,也是泛型类型的新手.

Sel*_*enç 10

由于T可以是任何类型,因此无法保证T会超载><运营商.添加一个IComparable<T>T必须实现的约束IComparable<T>包含一个名为的方法CompareTo,然后你可以使用该方法来比较你的对象:

public static T Greater<T>(ref T a, ref T b) where T : IComparable<T>
{
    if(a.CompareTo(b) > 0) return a;
    else return b;
}
Run Code Online (Sandbox Code Playgroud)