1.首先我们建立一个枚举类。 using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace ConsoleApp3{ public enum Fruit { apple, peach, watermelon, banana, orange }} 2.代
1.首先我们建立一个枚举类。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
public enum Fruit
{
apple,
peach,
watermelon,
banana,
orange
}
}
2.代码调用
using ConsoleApp3;
Console.WriteLine(Fruit.orange);
Console.WriteLine("Hello, World!");
3.当我们要使用中文的时候,这时候要进行变化,使用特性
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
public enum Fruit
{
[Description("苹果")]
apple,
[Description("桃子")]
peach,
[Description("西瓜")]
watermelon,
[Description("香蕉")]
banana,
[Description("橘子")]
orange
}
static class EnumExtensions
{
public static string GetDescription(this Enum val)
{
var field = val.GetType().GetField(val.ToString());
if (field == null)
return val.ToString();
var customAttribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)); //使用反射,反射效率低
return customAttribute == null ? val.ToString() : ((DescriptionAttribute)customAttribute).Description;
}
}
}
4.代码调用
using ConsoleApp3;
Console.WriteLine(Fruit.orange);
Console.WriteLine(Fruit.orange.GetDescription());
Console.WriteLine("Hello, World!");
5.如果我们有很多种类的水果的话,并且分类的话。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
public enum Fruit
{
[levelOne("一级")]
[Description("苹果")]
apple,
[levelOne("二级")]
[Description("桃子")]
peach,
[Description("西瓜")]
watermelon,
[levelOne("三级")]
[Description("香蕉")]
banana,
[levelOne("三级")]
[Description("橘子")]
orange
}
static class EnumExtensions
{
public static string GetDescription(this Enum val)
{
var field = val.GetType().GetField(val.ToString());
if (field == null)
return val.ToString();
var customAttribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)); //使用反射,反射效率低
return customAttribute == null ? val.ToString() : ((DescriptionAttribute)customAttribute).Description;
}
public static string Getlevel(this Enum val)
{
var field = val.GetType().GetField(val.ToString());
if(field == null)
return val.ToString();
var customAttribute = Attribute.GetCustomAttribute(field, typeof(levelOne));
return customAttribute == null ? val.ToString() : ((levelOne)customAttribute).Data;
}
}
public class levelOne : Attribute
{
public string Data { get; set; }
public levelOne() { }
public levelOne(string data)
{
Data = data;
}
}
}
6.代码调用
using ConsoleApp3;
Console.WriteLine(Fruit.orange);
Console.WriteLine(Fruit.orange.GetDescription());
Console.WriteLine(Fruit.orange.Getlevel());
Console.WriteLine(Fruit.apple.Getlevel());
Console.WriteLine("Hello, World!");