0

我有以下代码:

        var values1 = (EReferenceKey[])Enum.GetValues(typeof(EReferenceKey)); 
        var valuesWithNames = values1.Select(
            value => new {
                Value = ((int)value).ToString("00"),
                Text = Regex.Replace(value.ToString(), "([A-Z])", " $1").Trim() 
            });

这是stackoverflow上建议的一些代码,可以使此方法通用:

    public static IEnumerable<KeyValuePair<string, string>> GetValues2<T>() where T : struct {
        var t = typeof(T);
        if (!t.IsEnum)
            throw new ArgumentException("Not an enum type");
        return Enum.GetValues(t)
            .Cast<T>()
            .Select(x => new KeyValuePair<string, string>(
                ((int)Enum.ToObject(t, x)).ToString("00"), 
                Regex.Replace(x.ToString(), "([A-Z])", " $1").Trim()
                ));
    }

它给了我几乎相同的结果,但它缺少命名“值”和“文本”。有人可以向我建议如何修改后面的代码以添加这些代码并且仍然可以按顺序返回结果吗?

我确实尝试过自己做,但是当我尝试将“Value =”和“Text =”添加到泛型的选择中时,它给了我错误:

错误 6 当前上下文中不存在名称“值”

4

1 回答 1

2

您需要定义一个类,将返回其值:

public class YourValues
{
    public string Value {get; set;}
    public string Text {get; set;}
}

并像这样修改:

public static IEnumerable<YourValues> GetValues2<T>() where T : struct 
{
    var t = typeof(T);
    if (!t.IsEnum)
        throw new ArgumentException("Not an enum type");
    return Enum.GetValues(t)
        .Cast<T>()
        .Select(x => new YourValues{
            Value = ((int)Enum.ToObject(t, x)).ToString("00"), 
            Text = Regex.Replace(x.ToString(), "([A-Z])", " $1").Trim()
            });
}
于 2012-09-17T00:16:00.503 回答