2009-11-21 56 views
0

我一直在试图找到一个这样的答案一段时间....任何想法如何获得调用这里的所有方法?方法的调用('params'/ generic表兄弟)

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 

回答

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

天啊!我可以做得多笨!当然!!!谢谢 :) – 2009-11-21 03:56:32