简体   繁体   English

c#泛型方法:需要类型参数

[英]c# Generic methods: Type argument required

Getting error: 出现错误:

Using generic method 'Program.Sort3Vars(T[],T[],T[])' requires 1 type arguments. 使用通用方法'Program.Sort3Vars(T [],T [],T [])'需要1个类型参数。

Aren't they defined here? 他们不是在这里定义吗?

Sort3Vars<int, string, string>(cost, var1, var2);

This is for a sort algorithm I am making. 这是我正在做的排序算法。 I want to be able to sort by an integer or a string or a double etc. without having to write the same method multiple times with just a different datatype. 我希望能够按整数,字符串或双精度数等进行排序,而不必只用一个不同的数据类型多次编写相同的方法。

This is my code where I am getting the error. 这是我得到错误的代码。

namespace ConsoleApplication10
{
    class Program
    {
        public static int[] cost = { 2, 5, 3, 4, 2, 1 };
        public static double[] costdouble = { 2.5, 4.30, 3.33, 4, 2, 1.10 };
        public static string[] var1 = { "apple", "mango", "banana", "grapes", "chicken", "ham" };
        public static string[] var2 = { "fruit", "fruit", "fruit", "fruit", "meat", "meat", };

        static void Main(string[] args)
        {
            Sort3Vars<int, string, string>(cost, var1, var2);
            //Using generic method 'Program.Sort3Vars(T[],T[],T[])' requires 1 type arguments.
        }

        public static void Sort3Vars<T>(T[] tkey, T[] tvar1, T[] tvar2)
        {
            //sort tvar1, tvar2 by cost/tkey stub.
        }
    }
}

This is a method with 3 arguments and one generic parameter, T , that is the same for all 3 arguments. 这是一个具有3个参数和一个通用参数T ,这对于所有3个参数都是相同的。 You want a method with 3 generic parameters, one for each argument: 您需要一个带有3个通用参数的方法,每个参数一个:

public static void Sort3Vars<TKey, T1, T2>(TKey[] tkey, T1[] tvar1, T2[] tvar2)
{
    //sort tvar1, tvar2 by cost/tkey stub.
}

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

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