1

我有以下课程:

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;
}
4

3 回答 3

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);
于 2013-03-04T23:56:27.287 回答
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可能会容易得多。

于 2013-03-05T01:12:45.350 回答
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
于 2013-03-05T00:01:44.763 回答