如何将类型转换为枚举

时间:2014-03-13 10:16:37

标签: c# .net wpf enums

我试图从类型中获取枚举,我将解释,我有这个枚举(我使用字符串枚举),这些解释为here

public enum ENUM1
{
    [StringValue("CodeIP597")] Code = 1,
    [StringValue("InfoYes")] Info = 3
}

public enum ENUM2
{
    [StringValue("CodeNoIP")] Code = 1,
    [StringValue("Info95p")] Info = 3
}

方法"一般"是这样的:

private static void General(Type enumType)
{
   var Enu = enumType.toEnum();  //i want something like this
   Console.WriteLine(StringEnum.GetStringValue(Enu.Code));           
}

我有很多等于枚举每个都包含属性" Code"和"信息" ,所以我希望对于我作为参数放置的每个enumType,在变量控制台中返回字符串值。

例如: 如果我称这种方法

General(typeof(ENUM1));

控制台将是: CodeIP597

如果我称这种方法

General(typeof(ENUM2));

控制台将是: CodeNoIP

我该怎么办?感谢所有提前

3 个答案:

答案 0 :(得分:3)

假设您的属性看起来像这样:

public class StringValue : Attribute
{
    public string Name { get; private set; }
    public StringValue(string name)
    {
        this.Name = name;
    }
}

然后你必须使用反射来提取属性及其值,因为除了它们的值名之外,你的枚举之间没有任何关系:

private static void General(Type enumType)
{
    if (!enumType.IsEnum)
        throw new ArgumentException("Not an enum type");

    var values = enumType.GetFields();

    var code = values.First(f => f.Name == "Code");
    var info = values.First(f => f.Name == "Info");

    string codeString = code.GetCustomAttributes(false).OfType<StringValue>().First().Name;
    string infoString = info.GetCustomAttributes(false).OfType<StringValue>().First().Name;

    Console.WriteLine(codeString);
    Console.WriteLine(infoString);
}

它与输出方面的内容不完全相同,但演示了如何获取字符串值。您可能还需要添加其他检查,它们是您期望的类型或具有您期望的属性。

答案 1 :(得分:0)

您最好使用名为enum.GetValues();

的方法

答案 2 :(得分:0)

如果查看共享的代码项目链接中的GetStringValue(),则在处理之前将Enum值转换为字符串。您可以重写GetStringValue()以接受Typestring而不是键入的枚举值:

public static string GetStringValue(Type enumType, string valueStr)
{
    //Look for our 'StringValueAttribute' 
    //in the field's custom attributes
    FieldInfo fi = enumType.GetField(valueStr);
    StringValueAttribute[] attrs = 
       fi.GetCustomAttributes(typeof (StringValueAttribute), 
                               false) as StringValueAttribute[];
    if (attrs.Length > 0)
    {
        return attrs[0].Value;
    }

    return null;
}

我删除了缓存,因为它没有包含在函数中,但重新引入应该是一件容易的事。

相关问题