如果你想要数值,你可以使用Convert.ToInt32(selectedItem)
然后ToString()
对它做一个。如果enum
是基于int
. (从技术上讲,它会起作用,除非 的值对于enum
来说太大了int
)
现在,多亏了表达式树的魔力……两个类:
public static class EnumToString<T>
{
public static readonly Func<T, string> Do;
static EnumToString()
{
Type type = typeof(T);
if (!type.IsEnum)
{
throw new ArgumentException();
}
Type baseType = type.GetEnumUnderlyingType();
var par1 = Expression.Parameter(typeof(T));
var cast = Expression.Convert(par1, baseType);
Expression<Func<object, string>> toString = p => p.ToString();
var body = (MethodCallExpression)toString.Body;
var toString2 = Expression.Call(cast, body.Method);
Do = Expression.Lambda<Func<T, string>>(toString2, par1).Compile();
}
}
public static class EnumToObject<T>
{
public static readonly Func<T, object> Do;
static EnumToObject()
{
Type type = typeof(T);
if (!type.IsEnum)
{
throw new ArgumentException();
}
Type baseType = type.GetEnumUnderlyingType();
var par1 = Expression.Parameter(typeof(T));
var cast1 = Expression.Convert(par1, baseType);
var cast2 = Expression.Convert(cast1, typeof(object));
Do = Expression.Lambda<Func<T, object>>(cast2, par1).Compile();
}
}
static void Main()
{
string str = EnumToString<MyEnum>.Do(MyEnum.Foo); // "1"
object obj = EnumToObject<MyEnum>.Do(MyEnum.Foo); // (int)1
}
第一个,EnumToString<>
获取枚举值的值并将其转换为字符串。第二个将枚举值的值转换为其基本类型(无论它是什么)并返回一个object
(因此它将基值装箱)(.ToString()
例如,您可以在其上执行 a )。
要使用它们,您必须将您的类更改为:
IEnumerable<SelectListItem> GetAllEnumValues<T>()
{
// In truth, the array returned by Enum.GetValues **is** strongly typed
// but is "downcasted" to Array. So we re-upcast it.
T[] values = (T[])Enum.GetValues(typeof(T));
...
Value = EnumToString<T>.Do(selectedItem),
// or
Value = EnumToObject<T>.Do(selectedItem).ToString(),
}
但请注意,所有这些几乎都是无用的,因为有特殊的格式化程序d
:
MyEnum enu = MyEnum.Something; // (where MyEnum.Something == 1)
string str = enu.ToString("d"); // 1
Enum enu2 = enu;
string str2 = enu2.ToString("d"); // 1
请参阅枚举格式字符串