如何在C#中模拟Java通用通配符

use*_*069 2 c# java generics wildcard

以下Java代码比较两个数组的平均值,一个是整数,另一个是双数.

class Generic_Class<T extends Number>
{
    T[] nums; // array of Number or subclass

    Generic_Class(T[] o)
    {
        nums = o;
    }

    // Return type double in all cases.
    double average()
    {
        double sum = 0.0;

        for(int i=0; i < nums.length; i++)
            sum += nums[i].doubleValue();

        return sum / nums.length;
    }


//  boolean sameAvg(Generic_Class<T> ob)
//  Using Generic_Class<T> i get the error:
//  incompatible types: Generic_Class<Double> cannot be converted to Generic_Class<Integer>

//  Using wilcards I get no error
    boolean sameAvg(Generic_Class<?> ob)
    {
        if(average() == ob.average())
            return true;
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

主要方法是这样的:

public static void main(String args[])
{
    Integer inums[] = { 1, 2, 3, 4, 5 };
    Double  dnums[] = { 1.0, 2.0, 3.0, 4.0, 5.0 };

    Generic_Class<Integer> iob = new Generic_Class<Integer>(inums);
    Generic_Class<Double>  dob = new Generic_Class<Double>(dnums);

    System.out.println("iob average is " + iob.average());
    System.out.println("dob average is " + dob.average());

    if (iob.sameAvg(dob))
        System.out.println("Averages of iob and dob are the same.");
    else
        System.out.println("Averages of iob and dob differ.");
}
Run Code Online (Sandbox Code Playgroud)

结果是:

iob average is 3.0
dob average is 3.0
Averages of iob and dob are the same.
Run Code Online (Sandbox Code Playgroud)

我曾尝试在C#中做同样的事情但是,由于我没有通配符,我无法完成同样的任务.

我怎样才能用C#做同样的事情?

谢谢.

Swe*_*per 5

正如其他回答者所说,NumberC#中没有相应的内容.你能得到的最好的是struct, IConvertible.但是,还有另一种方法可以执行通用通配符.

只需使用另一个通用参数:

public class Generic_Class<T> where T : struct, IConvertible
{
    T[] nums;
    public Generic_Class(T[] o)
    {
        nums = o;
    }

    public double Average()
    {
        double sum = 0.0;
        for(int i=0; i < nums.Length; i++)
            sum += nums[i].ToDouble(null);
        return sum / nums.Length;
    }

    // this is the important bit
    public bool SameAvg<U>(Generic_Class<U> ob) where U : struct, IConvertible
    {
        if(Average() == ob.Average())
            return true;
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)