方法调用(使用“params”/泛型表兄弟)
一段时间以来我一直试图找到这个问题的答案......关于如何调用这里的所有方法有什么想法吗?
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
I've been trying to find an answer for this for a while.... Any ideas on how do I get to invoke all of the methods here?
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);
}
}
}
Answer:
//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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)