using System;
using System.Collections.Generic;
namespace csharp
{
// 1. 添加一个类(例如 Program 或 ArrayHelper)
class Program
{
// a,这是一个支持比较的泛型方法示例 查找最大值
//带泛型约束的方法:要求 T 必须实现 IComparable<T> 接口
public static T FindMax<T>(T[] array) where T : IComparable<T>
{
if (array == null || array.Length == 0)
throw new ArgumentException("数组不能为空");
T max = array[0];
//方法1
for (int i = 1; i < array.Length; i++)
{
if (array[i].CompareTo(max) > 0)
{
max = array[i];
}
}
return max;
}
//方法2
// foreach (T item in array)
// {
// // 使用 CompareTo 方法比较大小
// if (item.CompareTo(max) > 0)
// {
// max = item;
// }
// }
// return max;
//}
//b. 基础泛型方法:打印任意类型的数组 即 泛型方法处理不同基本类型的数组
public static void PrintArray<T>(T[] array)
{
foreach (T item in array)
{
Console.Write($"{item} ");
}
Console.WriteLine();
}
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3 };
string[] names = { "Alice", "Bob" };
PrintArray(numbers); // 输出:1 2 3 (后换行)
PrintArray(names); // 输出:Alice Bob (后换行)
// 2. 泛型方法查找最大值
Console.WriteLine("\n=== 查找最大值 ===");
Console.WriteLine($"数字数组最大值: {FindMax(numbers)}");
Console.WriteLine($"字符串数组最大值: {FindMax(names)}");
}
}
}