我有以下课程:
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!
我知道我必须使用Reflection迭代属性,但这对我不起作用。
我试图使用此功能,但这不起作用:
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;
}
答案 0 :(得分:3)
为什么不使用Enum类型?
public enum Task {
Bug,
Issue,
Feature
}
然后你可以从int转换它。
int i = 1;
Task myTask = (Task)i;
您也可以从字符串名称中获取它。
string s = "Bug";
Task bugType = Enum.Parse(typeof(Task), s);
答案 1 :(得分:2)
问题在于您尝试获取属性,但您的TaskType
对象是字段:
public static TaskType GetTaskType(int id)
{
FieldInfo[] fields = typeof(TaskType).GetFields(BindingFlags.Public | BindingFlags.Static);
foreach (FieldInfo field in fields)
{
TaskType t = (TaskType)field.GetValue(null);
if (t.value == id)
{
return t;
}
}
return null;
}
使用LINQ,这可以是一行代码:
public static TaskType GetTaskType(int id)
{
return typeof(TaskType)
.GetFields(BindingFlags.Public | BindingFlags.Static)
.Select(f => (f.GetValue(null) as TaskType))
.FirstOrDefault(t => t != null && t.value == id);
}
public static TaskType GetTaskType(string name)
{
return typeof(TaskType)
.GetFields(BindingFlags.Public | BindingFlags.Static)
.Select(f => (f.GetValue(null) as TaskType))
.FirstOrDefault(
t => t != null &&
t.name.Equals(name, StringComparison.InvariantCultureIgnoreCase));
}
但是,正如其他人已经提到的那样,enum
可能会容易得多。
答案 2 :(得分:1)
如果你真的坚持使用那个类定义并且不能使用枚举这样的东西,那么这里是工作代码,它通过反射获得名称:
int id = 1;
Type type = typeof(TaskType);
BindingFlags privateInstance = BindingFlags.NonPublic | BindingFlags.Instance;
var name = type
.GetFields(BindingFlags.Public | BindingFlags.Static)
.Select(p => p.GetValue(null))
.Cast<TaskType>()
.Where(t => (int)type.GetField("value", privateInstance).GetValue(t) == id)
.Select(t => (string)type.GetField("name", privateInstance).GetValue(t))
.FirstOrDefault();
// Output: Bug