我有以下课程:
public sealed class TaskType
{
private readonly String name;
private readonly int value;
public static readonly TaskType BUG = new TaskType(1, "Bug");
public static readonly TaskType ISSUE = new TaskType(2, "Issue");
public static readonly TaskType FEATURE = new TaskType(3, "Feature");
//more here
private TaskType(int value, String name)
{
this.name = name;
this.value = value;
}
public override string ToString()
{
return name;
}
}
如何从一个值中转换 TaskType:
int i = 1;
String name = (TaskType)i.ToString(); // this is where i am stuck!
我知道我必须使用反射来遍历属性,但这对我不起作用。
例如,我曾尝试使用此功能,但这不起作用:
private TaskType getTaskType(int id)
{
PropertyInfo[] properties = typeof(TaskType).GetProperties(BindingFlags.Public | BindingFlags.Static);
foreach (PropertyInfo property in properties)
{
TaskType t = (TaskType)property.GetValue(null, null);
if (t.ToValue() == id)
return t;
}
return null;
}