我正在尝试创建一个能够获取EnumValue的Namevalue的函数
例如:
Get_Enum_ValueName(DayOfWeek, 0)
...这将返回“星期日”。
但我的代码不起作用,它说类型没有定义:
Private Function Get_Enum_ValueName(Of T)(ByVal EnumName As T, ByVal EnumValue As Integer) As String
Return DirectCast([Enum].Parse(GetType(EnumName), EnumValue ), EnumName).ToString
End Function
答案 0 :(得分:30)
给出enum
public enum Week
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
以下是您可以做的事情:
static void Main(string[] args)
{
// enum to int
int i=(int)Week.Thursday;
// int to enum;
Week day=(Week)3;
// enum to string
string name=Week.Thursday.ToString();
string fun=Enum.GetName(typeof(Week), 6);
string agh=Enum.GetName(typeof(Week), Week.Monday);
string wed=EnumName(Week.Wednesday);
// string to enum
Week apt=(Week)Enum.Parse(typeof(Week), "Thursday");
// all values of an enum type
Week[] days=(Week[])Enum.GetValues(typeof(Week));
// all names of an enum type
string[] names=Enum.GetNames(typeof(Week));
}
static string EnumName<T>(T value)
{
return Enum.GetName(typeof(T), value);
}
答案 1 :(得分:8)
在C#中,那将是:
return Enum.ToObject(typeof(T), EnumValue).ToString();
或(同样):
return ((T)(object)(EnumValue)).ToString();
答案 2 :(得分:6)
public enum WeekDay
{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7
}
string s = WeekDay.Friday.ToString();
这简单......除非我误解了什么?
如果您只有号码:
string s = ((WeekDay)4).ToString();
<强>更新强>
好的,下次你应该提到你想要一些通用的......用于所有的枚举,而不只是那个具体的例子。你可以试试这个:
public static class EnumExtensions
{
public static T ToEnum<T>(this int value) where T : struct
{
return (T)(object)value;
}
public static string ToEnumName<T>(this int value) where T : struct
{
return ((T)(object)value).ToString();
}
}
像这样使用:
int someEnumValue = 4;
string name = someEnumValue.ToEnumName<WeekDay>();
或:
WeekDay weekDay = someEnumValue.ToEnum<WeekDay>();
我仍然认为这不是必要的,因为你仍然需要知道枚举的类型......因此:
这:string name = ((WeekDay)someEnumValue).ToString();
和string name = someEnumValue.ToEnumName<WeekDay>();
等同于......但是......无论什么适合你。