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 = , D=, C=, B=, A= };
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#做的好一些、要更加地方便使用。

最新文章

  1. Oracle监听服务启动失败案例
  2. 增量处理属性之记录模式(Record Modes)
  3. touch详解
  4. java 线上问题定位工具
  5. 当类库项目中无法使用Application.StartupPath
  6. 彩票APP将演绎“快鱼吃慢鱼”的发展轨迹
  7. Oracle开发专题之:%TYPE 和 %ROWTYPE
  8. 3、Android应用程序签名及发布
  9. Delphi XE6 for Android 让手机震动(调用Java的函数)
  10. Swift语言Auto Layout入门教程:上篇
  11. JavaWeb(三)JSP概述
  12. springboot学习(一)——helloworld
  13. kvm之十二:虚拟机迁移
  14. 《Head First JavaScript》 学习笔记
  15. 课程五(Sequence Models),第一 周(Recurrent Neural Networks) —— 2.Programming assignments:Dinosaur Island - Character-Level Language Modeling
  16. ORM版学员管理系统1
  17. jquery元素使用
  18. day32 并发编程
  19. Linux Mint安装Docker踩坑指南
  20. selenium.common.exceptions.WebDriverException: Message: "Can't load the profile.

热门文章

  1. 一个App完成入门篇(四)- 完成反馈页面
  2. 整理BOM时写的关于拆分单元格的VB代码
  3. Google 新推出Background sync API
  4. IOS 手势-轻点、触摸、手势、事件
  5. 关于基本类型值和引用类型值以及Vue官方API的array.$remove(reference)
  6. DDD~领域层
  7. C#教程(1) -- .Net与C#简介
  8. SQL SERVER 2005/2008 中关于架构的理解(一)
  9. 快速入门系列--NOSQL--07MongoDB
  10. python 反射的使用