在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#中提供了一種靈活的方式來處理復雜需求,讓你可以更容易地傳遞可變數量的參數。