C#基础-技术还债2-枚举

时间:2023-03-09 00:56:21
C#基础-技术还债2-枚举

定一个枚举如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text; namespace YX.Model.QianHai
{
public enum IdType
{
[Value("")]
身份证 = ,
[Value("")]
户口簿 = ,
[Value("")]
护照 = ,
[Value("")]
军官证 = ,
[Value("")]
士兵证 = ,
[Value("")]
港澳居民来往内地通行证 = ,
[Value("")]
*同胞来往内地通行证 = ,
[Value("")]
临时身份证 = ,
[Value("")]
外国人居留证 = ,
[Value("")]
警官证 = ,
[Value("X")]
其他证件 =
} public static class IdTypeExtentions
{
public static string GetValue(this IdType idType)
{
return ValueAttribute.GetCustomerValue(idType);
}
}
}

内涵一个该枚举类型的扩展方法。

由于最有一个枚举值是 引用类型,事实 枚举的值不支持 引用类型,只能获取到 值类型,

所以才有以下 自定义属性。

定义一个自定义属性:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text; namespace YX.Model
{
public class ValueAttribute : Attribute
{
public ValueAttribute(string value)
{
Value = value;
}
public string Value { get; private set; } public static string GetCustomerValue(object code)
{
var ty = code.GetType();
var name = Enum.GetName(ty, code);
FieldInfo field = ty.GetField(name);
ValueAttribute attr = Attribute.GetCustomAttribute(field, typeof(ValueAttribute)) as ValueAttribute;
return attr.Value;
}
}
}