有时做项目时遇到了一个棘手问题:需要写一个计算器方法,有时候计算两个数的和,有时候是三个数,有时候可能是十几个数...
传统做法需要写N个重载方法:
C#public int Sum(int a, int b) => a + b;
public int Sum(int a, int b, int c) => a + b + c;
public int Sum(int a, int b, int c, int d) => a + b + c + d;
// 无穷无尽...
这样写代码,累死程序员! 今天就来分享一个C#神器——params关键字,让你一行代码搞定所有情况,写出更优雅的代码!
params是C#中的一个强大特性,它允许方法接受可变数量的参数,让方法调用变得极其灵活。
C#namespace AppParams
{
internal class Program
{
static void Main(string[] args)
{
// 调用方式 - 超级灵活!
PrintNumbers(1, 2, 3); // 直接传递参数
PrintNumbers(new int[] { 1, 2, 3 }); // 传递数组
PrintNumbers(); // 不传参数也可以
}
private static void PrintNumbers(params int[] numbers)
{
foreach (var num in numbers)
{
Console.Write($"{num} ");
}
Console.WriteLine();
}
}
}

关键点: params参数必须是方法的最后一个参数!
C#namespace AppParams
{
public class Calculator
{
// 计算任意数量整数的和
public static int Sum(params int[] numbers)
{
int sum = 0;
foreach (int num in numbers)
{
sum += num;
}
return sum;
}
// 查找最大值
public static int Max(params int[] numbers)
{
if (numbers.Length == 0)
throw new ArgumentException("至少需要一个数字");
int max = numbers[0];
for (int i = 1; i < numbers.Length; i++)
{
if (numbers[i] > max)
max = numbers[i];
}
return max;
}
}
internal class Program
{
static void Main(string[] args)
{
// 使用示例 - 随心所欲
var sum1 = Calculator.Sum(1, 2, 3, 4, 5);
var sum2 = Calculator.Sum();
var max = Calculator.Max(10, 5, 8, 12, 3);
Console.WriteLine(sum1);
Console.WriteLine(sum2);
Console.WriteLine(max);
}
}
}

C#namespace AppParams
{
internal class Program
{
static void Main(string[] args)
{
// 🎯 使用示例 - 告别string.Format的繁琐
FormatAndPrint("Hello {0}, 你今年{1}岁了", "张三", 25);
FormatAndPrint("今日销售额:{0:C},订单数:{1}", 12580.5m, 88);
}
// ✨ 组合使用params和其他参数
public static void FormatAndPrint(string format, params object[] args)
{
Console.WriteLine(string.Format(format, args));
}
}
}

C#namespace AppParams
{
public class GenericPrinter<T>
{
public void PrintItems(params T[] items)
{
foreach (T item in items)
{
Console.WriteLine($"{item}");
}
}
}
internal class Program
{
static void Main(string[] args)
{
// 🚀 使用示例 - 类型安全又灵活
var stringPrinter = new GenericPrinter<string>();
stringPrinter.PrintItems("苹果", "香蕉", "橙子");
var numberPrinter = new GenericPrinter<int>();
numberPrinter.PrintItems(1, 2, 3, 4, 5);
}
}
}

.NET 9带来重大升级,params不再局限于数组,支持更多集合类型!
C#namespace AppParams9
{
internal class Program
{
static void Main(string[] args)
{
// 🎯 调用示例
PrintSumOfNumbers(1, 2, 3, 4, 5);
PrintSumOfNumbers(new[] { 1, 2, 3, 4, 5 });
PrintSumOfNumbers(new List<int> { 1, 2, 3, 4, 5 });
}
// ✨ 使用IEnumerable<T>
static void PrintSumOfNumbers(params IEnumerable<int> numbers)
{
var sum = numbers.Sum();
Console.WriteLine($"Sum of numbers : {sum}");
}
}
}

C#namespace AppParams9
{
internal class Program
{
static void Main(string[] args)
{
var numbers = new int[] { 1, 2, 3, 4, 5 };
// 🎯 调用示例
var result = SumEfficient(numbers);
Console.WriteLine(result);
}
// 🚀 使用ReadOnlySpan优化性能
public static int SumEfficient(params ReadOnlySpan<int> numbers)
{
int sum = 0;
foreach (var num in numbers)
{
sum += num;
}
return sum;
}
}
}

为什么用Span? 零内存分配,超高性能!
params会创建临时数组,频繁调用可能影响性能!
C#namespace AppParams9
{
public class OptimizedCalculator
{
// ✅ 常用情况的特定重载(性能最佳)
public static int Sum(int a, int b) => a + b;
public static int Sum(int a, int b, int c) => a + b + c;
// ✅ 处理其他情况的params重载
public static int Sum(params int[] numbers)
{
int sum = 0;
foreach (int num in numbers)
{
sum += num;
}
return sum;
}
}
internal class Program
{
static void Main(string[] args)
{
var result= OptimizedCalculator.Sum(1,2,3,4,5);
Console.WriteLine(result);
}
}
}
金句总结: 常用场景用重载,特殊场景用params!
params关键字是C#开发者的得力助手,它让代码更简洁、更优雅。随着.NET** 9的发布,params功能更加强大**,支持更多集合类型,性能也得到了提升。
💬 互动时间
你在项目中使用过params吗?遇到过哪些有趣的应用场景?欢迎在评论区分享你的经验!
觉得这篇文章对你有帮助,请转发给更多C#同行! 让我们一起写出更优雅的代码!🚀
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!