当前位置:首页>python>CSharp、Java、Go、Python 枚舉的用法

CSharp、Java、Go、Python 枚舉的用法

  • 2026-09-02 16:51:52
CSharp、Java、Go、Python 枚舉的用法

展示了一个多语言实现的算法演示程序,包含了Python、Go、C#和Java四种编程语言的版本。核心功能是通过枚举类型管理不同的图算法(如Dijkstra最短路径算法和Floyd-Warshall全源最短路径算法),并提供了交互式菜单供用户选择要运行的算法示例。所有版本都实现了:

枚举类型定义算法选项

中文名称映射

交互式菜单选择

算法示例执行功能

循环选择机制

各语言版本保持一致的架构和功能,展示了如何在不同的编程语言中实现相同的设计模式。代码结构清晰

python:

# encoding: utf-8# 版权所有  2026 ©涂聚文有限公司™ ®# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎# 描述:Algorithms# Author    : geovindu,Geovin Du 涂聚文.# IDE       : PyCharm 2024.3.6 python 3.11# os        : windows 10# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j# Datetime  : 2026/7/12 9:43# User      :  geovindu# Product   : PyCharm# Project   : PyAlgorithms# File      : CheckAlgorithms.pyimport asynciofrom enum import Enum, auto  # 导入枚举相关模块import Bll.FloydWarshallBllimport Bll.DijkstraBllclass Designlgorithm(Enum):    """    设计模式枚举 - 每个枚举成员对应一个设计模式的示例函数    """    Dijkstra = auto()    """    最短路径算法    """    FloydWarshall = auto()  #    """    全源最短路径算法    """    def show_example(self):        """        枚举成员方法:根据当前枚举值执行对应的示例函数        :return:'        """        pattern_handlers = {            Designlgorithm.Dijkstra: lambda: (Bll.DijkstraBll.DijkstraBll().demo()),            Designlgorithm.FloydWarshall: lambda: (Bll.FloydWarshallBll.FloydWarshallBll().demo()),        }        # 获取当前枚举对应的示例函数并执行        handler = pattern_handlers.get(self)        if handler:            print(f"\n===== 展示【{self.name} Pattern({self._name_to_cn(self.name)})】示例 =====")            handler()        else:            print(f"❌ 暂未实现{self.name}的示例")    @staticmethod    def _name_to_cn(name: str) -> str:        """        枚举名称转中文,提升可读性        :param name:        :return:        """        cn_map = {            "Dijkstra": "最短路径算法",            "FloydWarshall": "全源最短路径算法",        }        return cn_map.get(name, name)# encoding: utf-8# 版权所有  2026 ©涂聚文有限公司™ ®# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎# 描述:Algorithms# Author    : geovindu,Geovin Du 涂聚文.# IDE       : PyCharm 2024.3.6 python 3.11# os        : windows 10# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j# Datetime  : 2026/7/12 9:40# User      :  geovindu# Product   : PyCharm# Project   : PyAlgorithms# File      : main.pyimport sysimport iosys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')import Controller.CheckAlgorithmsdef select_design_pattern() -> tuple[int, Controller.CheckAlgorithms.Designlgorithm | None]:    """    返回 (序列号, 选中的枚举对象),退出则返回 (0, None)    :return:    """    print("\n=== 方式3:用户选择展示 ===")    print("可选设计模式(输入0或q退出):")    for idx, pattern in enumerate(Controller.CheckAlgorithms.Designlgorithm, 1):        print(f"{idx}. {pattern._name_to_cn(pattern.name)}({pattern.name})")    print("0. 退出")    while True:        user_input = input("\n请输入序号选择要展示的设计模式(输入0/q退出):").strip()        if user_input in ("0", "q", "Q"):            print("👋 退出选择流程")            return (0, None)        try:            choice = int(user_input)            if 1 <= choice <= len(Controller.CheckAlgorithms.Designlgorithm):                selected_pattern = list(Controller.CheckAlgorithms.Designlgorithm)[choice - 1]                print(f"✅ 你选择了序号:{choice}(对应{selected_pattern._name_to_cn(selected_pattern.name)})")                return (choice, selected_pattern)  # 返回(序列号, 枚举对象)            else:                print(f"❌ 输入无效!请输入1-{len(Controller.CheckAlgorithms.Designlgorithm)}之间的数字,或0/q退出")        except ValueError:            print("❌ 输入无效!请输入数字序号,或0/q退出")def ask_continue() -> bool:    """    询问用户是否继续选择,返回True(继续)/False(退出)    """    while True:        user_choice = input("\n是否继续选择其他设计模式?(y/n):").strip().lower()        if user_choice == "y":            return True        elif user_choice == "n":            print("👋 感谢使用,程序结束!")            return False        else:            print("❌ 输入无效!请输入 y(继续)或 n(退出)")if __name__ == '__main__':    # 方式1:用户输入选择展示(交互版)    '''    print("\n=== 方式1:用户选择展示 ===")    print("可选设计模式:")    for idx, pattern in enumerate( bll.CheckPatterns.DesignPattern, 1):        print(f"{idx}. {pattern._name_to_cn(pattern.name)}({pattern.name})")    try:        choice = int(input("\n请输入序号选择要展示的设计模式:"))        selected_pattern = list( bll.CheckPatterns.DesignPattern)[choice - 1]        selected_pattern.show_example()    except (ValueError, IndexError):        print("❌ 输入无效,请输入正确的序号!")    '''    # 2    print("🎉 设计模式示例展示程序")    while True:        # 1. 选择设计模式        selected_num, selected_pattern = select_design_pattern()        # 2. 判断是否直接退出(输入0/q)        if selected_num == 0:            print("👋 程序结束!")            break        # 3. 执行选中的示例        selected_pattern.show_example()        print(f"\n📌 本次选择的序列号是:{selected_num}")        # 4. 询问是否继续        if not ask_continue():            break  # 用户选择不继续,终止循环    print('hi,welcome geovindu.')

go:

/*# 版权所有  2026 ©涂聚文有限公司™ ®# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎# 描述:Algorithms# Author    : geovindu,Geovin Du 涂聚文.# IDE       : goLang 2024.3.6 go 26.2# os        : windows 10# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j# Datetime  : 2026/7/11 22:57# User      :  geovindu# Product   : GoLand# Project   : goalgorithms# File      : checkalgorithms.go*/package controllerimport (    "fmt"    "goalgorithms/bll")type DesignAlgorithms intconst (    Dijkstra DesignAlgorithms = iota    FloydWarshall)func(d DesignAlgorithms) String() string {    switch d {    case Dijkstra:        return "Dijkstra"    case FloydWarshall:        return "FloydWarshall"    default:        return "UNKNOWN"    }}// 4. 枚举转中文名称(和你 Python 一样)func(d DesignAlgorithms) ToChinese() string {    nameMap := map[DesignAlgorithms]string{        Dijkstra:      "最短路径算法",        FloydWarshall: "全源最短路径算法",    }    return nameMap[d]}// 5. 核心方法:ShowExample()func(d DesignAlgorithms) ShowExample() {    fmt.Println("\n===== 展示【" + d.String() + " Pattern(" + d.ToChinese() + ")】示例 =====")    // 映射:枚举 → 执行函数(和Python 的 pattern_handlers 完全一样)    switch d {    case Dijkstra:        bll.DijkstraMain() // 调用你的 bll 层    case FloydWarshall:        bll.FloydWarshallMain()        // ... 其他模式自己补全    default:        fmt.Println("❌ 暂未实现 " + d.String() + " 的示例")    }}/*# 版权所有  2026 ©涂聚文有限公司™ ®# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎# 描述: Algorithms# Author    : geovindu,Geovin Du 涂聚文.# IDE       : goLang 2024.3.6 go 26.2# os        : windows 10# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j# Datetime  : 2026/7/8 23:07# User      :  geovindu# Product   : GoLand# Project   : goalgorithms# File      : main.go*/package mainimport (    "bufio"    "fmt"    "goalgorithms/controller"    "os"    "strconv"    "strings")// 所有设计模式列表(和枚举顺序一致)var allPatterns = []controller.DesignAlgorithms{    controller.Dijkstra,    controller.FloydWarshall,}// selectDesignPattern 用户选择设计模式// 返回 (序号, 选中模式, 是否退出)funcselectDesignPattern() (int, controller.DesignAlgorithms, bool) {    fmt.Println("\n=== 方式3:用户选择展示 ===")    fmt.Println("可选设计模式(输入0或q退出):")    // 打印所有模式    for idx, pattern := range allPatterns {        fmt.Printf("%d. %s(%s)\n", idx+1, pattern.ToChinese(), pattern.String())    }    fmt.Println("0. 退出")    // 循环读取输入    for {        fmt.Print("\n请输入序号选择要展示的设计模式(输入0/q退出):")        // 读取一行输入        reader := bufio.NewReader(os.Stdin)        input, _ := reader.ReadString('\n')        input = strings.TrimSpace(input)        input = strings.ToLower(input)        // 退出逻辑        if input == "0" || input == "q" {            fmt.Println("👋 退出选择流程")            return 0, 0, true        }        // 转数字        choice, err := strconv.Atoi(input)        if err != nil {            fmt.Println("❌ 输入无效!请输入数字序号,或0/q退出")            continue        }        // 判断范围        if choice < 1 || choice > len(allPatterns) {            fmt.Printf("❌ 输入无效!请输入1-%d之间的数字,或0/q退出\n", len(allPatterns))            continue        }        // 选中        selected := allPatterns[choice-1]        fmt.Printf("✅ 你选择了序号:%d(对应%s)\n", choice, selected.ToChinese())        return choice, selected, false    }}// askContinue 询问是否继续funcaskContinue() bool {    for {        fmt.Print("\n是否继续选择其他设计模式?(y/n):")        reader := bufio.NewReader(os.Stdin)        input, _ := reader.ReadString('\n')        input = strings.TrimSpace(strings.ToLower(input))        if input == "y" {            return true        } else if input == "n" {            fmt.Println("👋 感谢使用,程序结束!")            return false        } else {            fmt.Println("❌ 输入无效!请输入 y(继续)或 n(退出)")        }    }}//TIP <p>To run your code, right-click the code and select <b>Run</b>.</p> <p>Alternatively, click// the <icon src="AllIcons.Actions.Execute"/> icon in the gutter and select the <b>Run</b> menu item from here.</p>funcmain() {    fmt.Println("🎉 设计模式示例展示程序")    for {        // 1. 选择模式        selectedNum, selectedPattern, isExit := selectDesignPattern()        if isExit {            fmt.Println("👋 程序结束!")            break        }        // 2. 展示示例        selectedPattern.ShowExample()        fmt.Printf("\n📌 本次选择的序列号是:%d\n", selectedNum)        // 3. 是否继续        if !askContinue() {            break        }    }}

c#

/* # encoding: utf-8# 版权所有  2026 ©涂聚文有限公司™ ®# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎# 描述: Algorithms# Author    : geovindu,Geovin Du 涂聚文.# IDE       : vs2026 c# .net 10# os        : windows 10# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j# Datetime  : 2026/07/04 22:16# User      :  geovindu# Product   : Visual Studio 2026# Project   : CSharpAlgorithms# File      : DesignAlgorithm.cs */using CSharpAlgorithms.Bll;using System;using System.Collections.Generic;using System.Text;namespace CSharpAlgorithms.Controller{    ///<summary>    /// 算法枚举,对应原 Designlgorithm    ///</summary>    public enum DesignAlgorithm    {        Dijkstra,        FloydWarshall    }    ///<summary>    ///    ///</summary>    public static class DesignAlgorithmExtensions    {        ///<summary>        /// 根据枚举执行对应示例        ///</summary>        publicstaticvoidShowExample(this DesignAlgorithm algorithm)        {            Dictionary<DesignAlgorithm, Action> patternHandlers = new()        {            { DesignAlgorithm.Dijkstra, () => new DijkstraBll().Demo() },            { DesignAlgorithm.FloydWarshall, () => new FloydWarshallBll().Demo() }        };            if (patternHandlers.TryGetValue(algorithm, out var handler))            {                string cnName = NameToCn(algorithm.ToString());                Console.WriteLine($"\n===== 展示【{algorithm} Pattern({cnName})】示例 =====");                handler.Invoke();            }            else            {                Console.WriteLine($"❌ 暂未实现{algorithm}的示例");            }        }        ///<summary>        /// 枚举名称转中文        ///</summary>        privatestaticstringNameToCn(string name)        {            Dictionary<string, string> cnMap = new()        {            { "Dijkstra", "最短路径算法" },            { "FloydWarshall", "全源最短路径算法" }        };            return cnMap.TryGetValue(name, out var val) ? val : name;        }        ///<summary>        /// 对外获取中文名称(菜单遍历使用)        ///</summary>        publicstaticstringGetCnName(this DesignAlgorithm algorithm)        {            return NameToCn(algorithm.ToString());        }    }}/* # encoding: utf-8# 版权所有  2026 ©涂聚文有限公司™ ®# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎# 描述: Algorithms# Author    : geovindu,Geovin Du 涂聚文.# IDE       : vs2026 c# .net 10# os        : windows 10# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j# Datetime  : 2026/07/04 22:16# User      :  geovindu# Product   : Visual Studio 2026# Project   : CSharpAlgorithms# File      : Program.cs */using CSharpAlgorithms.Controller;using CSharpAlgorithms.Dijkstra;using System.Text;namespace CSharpAlgorithms{    ///<summary>    ///    ///</summary>    internal class Program    {        ///<summary>        ///        ///</summary>        ///<param name="args"></param>        staticvoidMain(string[] args)        {            // 控制台强制UTF8输出,对应Python sys.stdout编码设置            Console.OutputEncoding = Encoding.UTF8;            Console.InputEncoding = Encoding.UTF8;            Console.WriteLine("🎉 算法示例展示程序");            while (true)            {                // 1. 用户选择算法                var selectResult = SelectAlgorithm();                int selectedNum = selectResult.Item1;                DesignAlgorithm? selectedPattern = selectResult.Item2;                // 输入0/q退出主循环                if (selectedNum == 0)                {                    Console.WriteLine("👋 程序结束!");                    break;                }                // 执行选中算法示例                selectedPattern!.Value.ShowExample();                Console.WriteLine($"\n📌 本次选择的序列号是:{selectedNum}");                // 是否继续选择                if (!AskContinue())                {                    break;                }            }            Console.WriteLine("hi,welcome geovindu.");        }        #region 工具方法        ///<summary>        /// 弹出选择菜单,返回(序号,枚举对象),(0,null)代表退出        ///</summary>        static (int, DesignAlgorithm?) SelectAlgorithm()        {            Console.WriteLine("\n=== 方式3:用户选择展示 ===");            Console.WriteLine("可选算法(输入0或q退出):");            // 遍历枚举输出菜单            var allAlgorithms = Enum.GetValues(typeof(DesignAlgorithm)).Cast<DesignAlgorithm>().ToList();            for (int i = 0; i < allAlgorithms.Count; i++)            {                var item = allAlgorithms[i];                Console.WriteLine($"{i + 1}. {item.GetCnName()}({item})");            }            Console.WriteLine("0. 退出");            while (true)            {                Console.Write("\n请输入序号选择要展示的算法(输入0/q退出):");                string? userInput = Console.ReadLine()?.Trim() ?? string.Empty;                // 退出指令                if (userInput is "0" or "q" or "Q")                {                    Console.WriteLine("👋 退出选择流程");                    return (0, null);                }                // 解析数字序号                if (!int.TryParse(userInput, out int choice))                {                    Console.WriteLine("❌ 输入无效!请输入数字序号,或0/q退出");                    continue;                }                // 范围校验                int maxIndex = allAlgorithms.Count;                if (choice < 1 || choice > maxIndex)                {                    Console.WriteLine($"❌ 输入无效!请输入1-{maxIndex}之间的数字,或0/q退出");                    continue;                }                DesignAlgorithm target = allAlgorithms[choice - 1];                Console.WriteLine($"✅ 你选择了序号:{choice}(对应{target.GetCnName()})");                return (choice, target);            }        }        ///<summary>        /// 询问是否继续选择 y/n        ///</summary>        staticboolAskContinue()        {            while (true)            {                Console.Write("\n是否继续选择其他算法?(y/n):");                string? input = Console.ReadLine()?.Trim().ToLower() ?? string.Empty;                if (input == "y")                    return true;                if (input == "n")                {                    Console.WriteLine("👋 感谢使用,程序结束!");                    return false;                }                Console.WriteLine("❌ 输入无效!请输入 y(继续)或 n(退出)");            }        }        #endregion    }}

java

/** * encoding: utf-8 * 版权所有 2026 ©涂聚文有限公司 ® * 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎 * 描述:Algorithms * Author    : geovindu,Geovin Du 涂聚文. * IDE       : IntelliJ IDEA 2024.3.6 Java 17 * # database  : Oracle21c,MySQL 9.0,SQL Server 2019,PostgreSQL 17.1 Neo4j * # OS        : window10 * Datetime  : 2026 - 2026/7/12 - 11:42 * User      : geovindu * Product   : IntelliJ IDEA * Project   : JavaAlgorithms * File      : DesignAlgorithm.java * explain   : 学习  类 **/package Controller;import Bll.DijkstraBll;import Bll.FloydWarshallBll;import java.util.HashMap;import java.util.Map;public enum DesignAlgorithm {    Dijkstra,    FloydWarshall;    private static final Map<String, String> CN_MAP;    private static final Map<DesignAlgorithm, Runnable> HANDLERS;    static {        CN_MAP = new HashMap<>();        CN_MAP.put("Dijkstra", "最短路径算法");        CN_MAP.put("FloydWarshall", "全源最短路径算法");        HANDLERS = new HashMap<>();        HANDLERS.put(Dijkstra, () -> new DijkstraBll().demo());        HANDLERS.put(FloydWarshall, () -> new FloydWarshallBll().demo());    }    public void showExample() {        Runnable handler = HANDLERS.get(this);        if (handler != null) {            String cnName = nameToCn(this.name());            System.out.printf("\n===== 展示【%s Pattern(%s)】示例 =====%n", this.name(), cnName);            handler.run();        } else {            System.out.printf("❌ 暂未实现%s的示例%n", this.name());        }    }    public static String nameToCn(String name) {        return CN_MAP.getOrDefault(name, name);    }}/** * encoding: utf-8 * 版权所有 2026 ©涂聚文有限公司 ® * 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎 * 描述:  Algorithms * Author    : geovindu,Geovin Du 涂聚文. * IDE       : IntelliJ IDEA 2024.3.6 Java 17 * # database  : Oracle21c,MySQL 9.0,SQL Server 2019,PostgreSQL 17.1 Neo4j * # OS        : window10 * Datetime  : 2026 - 2026/7/9 - 22:55 * User      : geovindu * Product   : IntelliJ IDEA * Project   : JavaAlgorithms * File      : Main.java * explain   : 学习  类 **/import Controller.*;import javax.imageio.ImageIO;import java.awt.*;import java.awt.image.BufferedImage;import java.io.File;import java.util.*;import java.util.List;import java.util.stream.Collectors;public class Main {    private static final Scanner SCANNER = new Scanner(System.in);    // 局部创建Scanner,用完不提前关闭,判断hasNextLine再读取    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        System.out.println("🎉 算法示例展示程序");        while (true) {            SelectResult result = selectAlgorithm(scanner);            int selectedNum = result.num;            DesignAlgorithm selectedPattern = result.pattern;            if (selectedNum == 0) {                System.out.println("👋 程序结束!");                break;            }            selectedPattern.showExample();            System.out.printf("\n📌 本次选择的序列号是:%d%n", selectedNum);            if (!askContinue(scanner)) {                break;            }        }        System.out.println("hi,welcome geovindu.");        scanner.close();    }    static class SelectResult {        int num;        DesignAlgorithm pattern;        SelectResult(int num, DesignAlgorithm pattern) {            this.num = num;            this.pattern = pattern;        }    }    private static SelectResult selectAlgorithm(Scanner scanner) {        System.out.println("\n=== 方式3:用户选择展示 ===");        System.out.println("可选算法(输入0或q退出)");        List<DesignAlgorithm> allAlgorithms = Arrays.asList(DesignAlgorithm.values());        for (int i = 0; i < allAlgorithms.size(); i++) {            DesignAlgorithm item = allAlgorithms.get(i);            String cn = DesignAlgorithm.nameToCn(item.name());            System.out.printf("%d. %s(%s)%n", i + 1, cn, item.name());        }        System.out.println("0. 退出");        while (true) {            System.out.print("\n请输入序号选择要展示的算法(输入0/q退出):");            // 关键:先判断是否存在输入再读取,防止抛异常            if (!scanner.hasNextLine()) {                return new SelectResult(0, null);            }            String input = scanner.nextLine().trim();            if ("0".equals(input) || "q".equalsIgnoreCase(input)) {                System.out.println("👋 退出选择流程");                return new SelectResult(0, null);            }            int choice;            try {                choice = Integer.parseInt(input);            } catch (NumberFormatException e) {                System.out.println("❌ 输入无效!请输入数字序号,或0/q退出");                continue;            }            int max = allAlgorithms.size();            if (choice < 1 || choice > max) {                System.out.printf("❌ 输入无效!请输入1-%d之间的数字,或0/q退出%n", max);                continue;            }            DesignAlgorithm target = allAlgorithms.get(choice - 1);            String cnName = DesignAlgorithm.nameToCn(target.name());            System.out.printf("✅ 你选择了序号:%d(对应%s)%n", choice, cnName);            return new SelectResult(choice, target);        }    }    private static boolean askContinue(Scanner scanner) {        while (true) {            System.out.print("\n是否继续选择其他算法?(y/n):");            // 增加输入存在判断,解决 NoSuchElementException            if (!scanner.hasNextLine()) {                System.out.println("👋 输入流中断,程序退出!");                return false;            }            String input = scanner.nextLine().trim().toLowerCase();            if ("y".equals(input)) {                return true;            }            if ("n".equals(input)) {                System.out.println("👋 感谢使用,程序结束!");                return false;            }            System.out.println("❌ 输入无效!请输入 y(继续)或 n(退出)");        }    }}

最新文章

随机文章