调用方法(使用'params'/ generic cousins)

时间:2009-11-21 03:33:36

标签: c# c#-2.0

我一直试图找到这个问题的答案......关于如何在这里调用所有方法的任何想法?

using System;

namespace ThinkFarAhead.Examples
{
    public class Params
    {

        public static void Main()
        {
            Max(1, 2);
            Max(1);  //Invokes #2?... Invokes #1 actually
            Max<int>(1, 2);
            Max<long>(1);  //Invokes #4?...  Invokes #3
        }

        //#1
        public static int Max(int first, params int[] values)
        {
            if (values.Length == 0)
            {
                Console.WriteLine("[1] Param #1: {0}", first);
                return 0;
            }

            Console.WriteLine("[1] Param #2: {0}", values[0]);
            return default(int);
        }



        //#2
        public static int Max(params int[] values)
        {
            Console.WriteLine("[2] Param #1: {0}", values[0]);
            return default(int);
        }

        //#3
        public static T Max<T>(T first, params T[] values)
        {
            if (values.Length == 0)
            {
                Console.WriteLine("[3] Param #1: {0}", first);
                return default(T);
            }

            Console.WriteLine("[3] Param #2: {0}", values[0]);
            return default(T);
        }

        //#4
        public static T Max<T>(params T[] values)
        {
            Console.WriteLine("[4] Param #1: {0}", values[0]);
            return default(T);
        }
    }
}

答案:

        //Normal method takes precedence over its generic cousin...  
        //Explicit parameter mappings take precedence over params match
        Max(1, 2);  

        Max(new[] {1});  //Single array of ints
        Max<int>(1, 2); //Can't pick generic equivalent unless explicitly called
        Max(new []{1L});  //Single array of longs 

1 个答案:

答案 0 :(得分:2)

Max(new int[]{1}); // Invokes 2.
Max<long>(new long[] { 1 }); // Invokes 4.