在C#中,params
关键字允许你在调用方法时传递可变数量的参数。这在处理复杂需求时非常有用,因为它可以让你更灵活地传递参数。以下是一些使用params
应对复杂需求的示例:
public void AddElements(params int[] elements)
{
foreach (int element in elements)
{
myCollection.Add(element);
}
}
// 调用方法
AddElements(1, 2, 3, 4, 5);
public void PrintMessage(params string[] messages)
{
foreach (string message in messages)
{
if (message.Contains("error"))
{
Console.WriteLine("Error: " + message);
}
else
{
Console.WriteLine(message);
}
}
}
// 调用方法
PrintMessage("This is a normal message.", "An error occurred.");
public void PerformOperation(int number, params string[] operations)
{
int result = number;
foreach (string operation in operations)
{
switch (operation)
{
case "add":
result += 1;
break;
case "subtract":
result -= 1;
break;
case "multiply":
result *= 2;
break;
case "divide":
result /= 2;
break;
}
}
Console.WriteLine("Result: " + result);
}
// 调用方法
PerformOperation(5, "add", "multiply");
params
传递自定义对象:public class CustomObject
{
public string Name { get; set; }
public int Value { get; set; }
}
public void ProcessObjects(params CustomObject[] objects)
{
foreach (CustomObject obj in objects)
{
Console.WriteLine("Name: " + obj.Name + ", Value: " + obj.Value);
}
}
// 调用方法
ProcessObjects(new CustomObject { Name = "Object1", Value = 1 }, new CustomObject { Name = "Object2", Value = 2 });
总之,params
关键字在C#中提供了一种灵活的方式来处理复杂需求,让你可以更容易地传递可变数量的参数。