温馨提示×

如何在C#中实现switch语句的动态化

c#
小樊
92
2024-08-13 17:07:40
栏目: 编程语言

在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语句,具体选择哪种取决于个人偏好和实际情况。

0