using System;class Test
{
static void Main()
{
Console.WriteLine(Max(1)); // 输出: 1
Console.WriteLine(Max(.3, -.5)); // 输出: 0.3
Console.WriteLine(Max(0M, -3M, 3.14M)); // 输出: 3.14
Console.WriteLine(Max(9f, -1f, 3.14f, -2.718f)); // 输出: 9
Console.WriteLine(Max(0u, 23u, 3114u, 120718u, 5678u)); // 输出: 120718
} /* 小测试:请问要实现以上功能需要在这里添加什么代码,尽可能短小些 */
}
{
static void Main()
{
Console.WriteLine(Max(1)); // 输出: 1
Console.WriteLine(Max(.3, -.5)); // 输出: 0.3
Console.WriteLine(Max(0M, -3M, 3.14M)); // 输出: 3.14
Console.WriteLine(Max(9f, -1f, 3.14f, -2.718f)); // 输出: 9
Console.WriteLine(Max(0u, 23u, 3114u, 120718u, 5678u)); // 输出: 120718
} /* 小测试:请问要实现以上功能需要在这里添加什么代码,尽可能短小些 */
}
static object Max(params object[] args)
{
System.Collections.ArrayList list = new System.Collections.ArrayList(args.Length - 1);
list.AddRange(args);
list.Sort();
return list[args.Length - 1];
}
static object Max(params object[] args)
{
if(args.Length==0) return null;
System.Collections.ArrayList list = new System.Collections.ArrayList(args.Length);
list.AddRange(args);
list.Sort();
return list[args.Length - 1];
}
static T? Max<T>(params T[] x)
where T: struct, IComparable
{
if (x.Length == 0) return null;
T a = x[0];
foreach (T i in x)
if (a.CompareTo(i) < 0) a = i;
return a;
}
Console.WriteLine(Max<int>()); // 输出: (空)
否则会报告以下编译错误:
console.cs(7,23): error CS0411: 无法从用法中推导出方法“Test.Max<T>(params T[])”的类型参数。请尝试显式指定类型参数。
static object Max(params object[] args)
{
object vResult = null;
foreach(object o in args)
if (o is IComparable && (o as IComparable).CompareTo(vResult) > 0)
{
vResult = o;
}
return vResult;
}