using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public enum MyEnum
{
[StringValue("Value 1")]
Value1,
[StringValue("Value 2")]
Value2,
[StringValue("Value 3")]
Value3
}
public class StringValueAttribute : Attribute
{
private readonly string _value;
public StringValueAttribute(string value)
{
_value = value;
}
public string Value
{
get { return _value; }
}
}
public class Program
{
public static void Main(string[] args)
{
List<string> enumList = Enum.GetValues(typeof(MyEnum))
.Cast<MyEnum>()
.Select(e => GetStringValue(e))
.ToList();
foreach (string value in enumList)
{
Console.WriteLine(value);
}
}
public static string GetStringValue(MyEnum value)
{
Type type = value.GetType();
MemberInfo[] memberInfo = type.GetMember(value.ToString());
StringValueAttribute attribute = memberInfo[0]
.GetCustomAttributes(typeof(StringValueAttribute), false)
.FirstOrDefault() as StringValueAttribute;
return attribute != null ? attribute.Value : value.ToString();
}
}GetStringValue
方法的参数类型改为 MyEnum
,以匹配 Func<MyEnum, string>
委托。现在,应该能够正确编译并输出枚举类型的字符串值