简体   繁体   English

如何使用泛型类型的运算符

[英]How to use operators with generic types

I want to make some generic methods like this one 我想制作一些像这样的通用方法

public static T maxValue(T value1, T value2 )       
{
    if(value1>value2)
        return value1;
    else
       return value2;    
}

And use it like 并使用它

max<string>.maxValue("john","john");

My question is what should be the return type of the maxValue function and how to use operators like + , = , < , > etc with generic types? 我的问题是maxValue函数的返回类型应该是什么,以及如何使用泛型类型的+=<>等运算符?

I know that T has no defined data type. 我知道T没有定义的数据类型。 I need the improvement this code. 我需要改进这段代码。

You can do this. 你可以这样做。 This, you can use for comparisons like == , > , < etc., but not for operations like + , - . 这个,您可以用于比较==><等,但不能用于+-等操作。

Here, we are using for > (return type would be T, same as input types) 这里,我们使用的是> (返回类型为T,与输入类型相同)

public static T maxValue<T>(T value1, T value2) where T : IComparable<T>
{
    if (value1.CompareTo(value2) > 0)
        return value1;
    else
        return value2;
}

Usage 用法

var maxInt = maxValue(3, 7); //=> 7
var maxDouble = maxValue(34.89d, -9.6d); //=> 34.89

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

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