gpt4 book ai didi

c# - 从 id 转换静态只读属性

转载 作者:太空宇宙 更新时间:2023-11-03 19:17:20 24 4
gpt4 key购买 nike

我有以下类(class):

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

最佳答案

为什么不直接使用枚举类型呢?

public enum Task {
Bug,
Issue,
Feature
}

然后你可以从一个 int 中转换它。

int i = 1;
Task myTask = (Task)i;

也可以从字符串名称中获取。

string s = "Bug";
Task bugType = Enum.Parse(typeof(Task), s);

关于c# - 从 id 转换静态只读属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15213327/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com