现在定义了一个名为People的枚举类型[System.SerializableAttribute()]
public enum People {
/// <res/>
[System.Xml.Serialization.XmlEnumAttribute("Sam")]
Item0,
/// <res/>
[System.Xml.Serialization.XmlEnumAttribute("John")]
Item1,
/// <res/>
[System.Xml.Serialization.XmlEnumAttribute("Jimmy")]
Item2,
}现在想通过一个函数string GetAttribue(Type type, string itemname)实现获取People枚举类型的属性值,就是GetAttribue(typeof(People), "Item0")返回"Sam",GetAttribue(typeof(People), "Item1")返回"John",GetAttribue(typeof(People), "Item2")返回"Jimmy"
那么GetAttribute该如何实现?
public enum People {
/// <res/>
[System.Xml.Serialization.XmlEnumAttribute("Sam")]
Item0,
/// <res/>
[System.Xml.Serialization.XmlEnumAttribute("John")]
Item1,
/// <res/>
[System.Xml.Serialization.XmlEnumAttribute("Jimmy")]
Item2,
}现在想通过一个函数string GetAttribue(Type type, string itemname)实现获取People枚举类型的属性值,就是GetAttribue(typeof(People), "Item0")返回"Sam",GetAttribue(typeof(People), "Item1")返回"John",GetAttribue(typeof(People), "Item2")返回"Jimmy"
那么GetAttribute该如何实现?
using System.Reflection;[System.SerializableAttribute()]
public enum People
{
/// <res/>
[System.Xml.Serialization.XmlEnumAttribute("Sam")]
Item0, /// <res/>
[System.Xml.Serialization.XmlEnumAttribute("John")]
Item1, /// <res/>
[System.Xml.Serialization.XmlEnumAttribute("Jimmy")]
Item2,}private void button1_Click(object sender, EventArgs e)
{
Text = GetAttribue(typeof(People), "Item0");
}public static string GetAttribue(Type type, string itemname)
{
FieldInfo vFieldInfo = type.GetField(itemname);
Attribute vAttribute = Attribute.GetCustomAttribute(
vFieldInfo, typeof(System.Xml.Serialization.XmlEnumAttribute));
if (vAttribute != null)
return ((System.Xml.Serialization.XmlEnumAttribute)vAttribute).Name;
else return itemname;
}