在C#中,可以使用字典(Dictionary)或者委托(Delegate)來實現switch語句的動態化。以下是使用字典的方法:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<string, Action> switchCases = new Dictionary<string, Action>
{
{ "case1", () => Console.WriteLine("Case 1") },
{ "case2", () => Console.WriteLine("Case 2") },
{ "case3", () => Console.WriteLine("Case 3") }
};
string userInput = "case2";
if (switchCases.ContainsKey(userInput))
{
switchCases[userInput].Invoke();
}
else
{
Console.WriteLine("Invalid case");
}
}
}
另一種方法是使用委托來實現動態化的switch語句,如下所示:
using System;
class Program
{
delegate void CaseHandler();
static void Main()
{
string userInput = "case2";
CaseHandler switchCase = null;
switch (userInput)
{
case "case1":
switchCase = Case1;
break;
case "case2":
switchCase = Case2;
break;
case "case3":
switchCase = Case3;
break;
default:
Console.WriteLine("Invalid case");
break;
}
switchCase?.Invoke();
}
static void Case1()
{
Console.WriteLine("Case 1");
}
static void Case2()
{
Console.WriteLine("Case 2");
}
static void Case3()
{
Console.WriteLine("Case 3");
}
}
以上兩種方法都可以實現動態化的switch語句,具體選擇哪種取決于個人偏好和實際情況。