科普扫盲贴:C#可以实现更好的“枚举类”
C#因为具有泛型、索引器等无比简洁的语法,所以实现“枚举类”更加简单优雅。
可是有些学Java的菜鸟却死抱着腐朽的Java不放。特此扫盲。
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{ class EnumMap<T> { private Dictionary<T, object> values { get; set; } public EnumMap() { values = new Dictionary<T, object>(); Enum.GetValues(typeof(T)).Cast<T>().ToList().ForEach(x => values.Add(x, new object())); } public object this[T index] { get { return values[index]; } set { values[index] = value; } } } class Program { enum Student { Name, Grade, Class }; static void Main(string[] args) { var student1 = new EnumMap<Student>(); student1[Student.Name] = "王二弟"; student1[Student.Grade] = 1; student1[Student.Class] = 7; Console.WriteLine(student1[Student.Name]); } }}