C# 与 Java 中的枚举
C#代码: 利用扩展方法,扩展枚举功能
using System; using System.Collections.Generic; using System.Text; using System.Linq; namespace EnumExtension { // Define an extension method in a non-nested static class. public static class Extensions { public static Grades minPassing = Grades.D; public static bool Passing(this Grades grade) { return grade >= minPassing; } } public enum Grades { F = 0, D=1, C=2, B=3, A=4 }; class Program { static void Main(string[] args) { Grades g1 = Grades.D; Grades g2 = Grades.F; Console.WriteLine("First {0} a passing grade.", g1.Passing() ? "is" : "is not"); Console.WriteLine("Second {0} a passing grade.", g2.Passing() ? "is" : "is not"); Extensions.minPassing = Grades.C; Console.WriteLine("\r\nRaising the bar!\r\n"); Console.WriteLine("First {0} a passing grade.", g1.Passing() ? "is" : "is not"); Console.WriteLine("Second {0} a passing grade.", g2.Passing() ? "is" : "is not"); } } } } /* Output: First is a passing grade. Second is not a passing grade. Raising the bar! First is not a passing grade. Second is not a passing grade. */
Java代码:
package com.mmb.csharp; /** * 颜色枚举 * */ public enum Color { /** * 1 */ RED("红色", 1), /** * 2 */ GREEN("绿色", 2), /** * 3 */ BLACK("黑色", 3), /** * 4 */ YELLOW("黄色", 4); // 成员变量 private String name; private int index; // 构造方法 private Color(String name, int index) { this.name = name; this.index = index; } // 普通方法 public static String getName(int index) { for (Color c : Color.values()) { if (c.getIndex() == index) { return c.name; } } return null; } public static Color getColor(int index) { for (Color c : Color.values()) { if (c.getIndex() == index) { return c; } } return null; } // get set 方法 public String getName() { return name; } public void setName(String name) { this.name = name; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } }
单单只着眼于枚举,Java要比C#做的好一些、要更加地方便使用。
分类:
[01-2].NET-C#
, [00-4]学习笔记
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
2011-02-18 监控 WebBrowser 控件内容的改变
2011-02-18 C# WebBrowser 常用设置项