2012-03-07 168 views
5

字符的解析字符串如果我有一个枚举匹配枚举值

public enum Action 
{ 
    None, 
    Address = 'A', 
    Amendment = 'C', 
    Normal = 'N' 
} 

什么是解析一个字符串来匹配相应的枚举字符,如果没有找到匹配无的最佳途径。 TryParse匹配名称而不是值。

举例来说,如果我有字符串为“C”我会想Action.Amendement提前

感谢

+2

“我有一个char的枚举” - 不,你没有:)你有一个int的枚举,其值是用字符文字指定的。 – porges 2012-03-07 08:53:48

+0

@Porges感谢您的澄清! – m4rc 2012-03-07 08:58:31

回答

5
char c = 'C'; // existent value 
var action = Enum.GetValues(typeof(Action)).Cast<Action>().FirstOrDefault(a => (char)a == c); 
// action = Action.Amendment 

和:

char c = 'X'; // non existent value 
var action = Enum.GetValues(typeof(Action)).Cast<Action>().FirstOrDefault(a => (char)a == c); 
// action = Action.None 
+0

Brilliant!这就像我想要的那样工作:-)谢谢 – m4rc 2012-03-07 09:04:08

4

只投它:

Action f = (Action)'C'; 

如果你有一个字符串并且正面至少有1个字符可以做:

Action f = (Action)"C"[0]; 
+0

我想他想用''X''得到'Action.None',例如因为''X''不是枚举的有效值。 – 2012-03-07 08:58:05

+0

@DarinDimitrov是的,我注意到了。这就是为什么我提高了你的答案 – 2012-03-07 08:58:42

+0

这是更清洁,你和“我们不需要LINQ”解析一个枚举,我们一直在解析2003年以来的枚举!“omg,ffs。 – b0rg 2012-03-07 09:42:17

0

枚举是数字类型的幕后。您可以尝试公共字符串类:

public class Action() 
{ 
    public const string A = "Address"; 
    public const string C = "Amendment"; 
} 

如果你想这样做2种方式,那么你可能需要使用2有道词典收集。

3

我会亲自留下它们作为整数,并使用DescriptionAttributes和工具类来获取该类型的描述属性。那么你可以使用不仅仅是一个角色来显示你想要的东西。

一个例子是:

/// <summary> 
    /// Returns the string value defined by the description attribute of the given enum. 
    /// If no description attribute is available, then it returns the string representation of the enum. 
    /// </summary> 
    /// <param name="value">Enum to use</param> 
    /// <returns>String representation of enum using Description attribute where possible</returns> 
    public static string StringValueOf(Enum value) 
    { 
     FieldInfo fi = value.GetType().GetField(value.ToString()); 
     DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); 
     if (attributes.Length > 0) 
     { 
      return attributes[0].Description; 
     } 
     else 
     { 
      return value.ToString(); 
     } 
    } 

其中你的枚举被定义为类似的东西;

public enum Action 
{ 
    None, 
    [DescriptionAttribute("A")] 
    Address, 
    [DescriptionAttribute("C")] 
    Amendment, 
    [DescriptionAttribute("N")] 
    Normal 
} 
+0

谢谢,我不知道有关DescriptionAttributes。这帮助我(与一个不同的问题,但仍然...) – 2013-10-24 08:22:26

+0

@DanielGruszczyk - 没有probs。你不限于DescriptionAttributes任何[Cust omAttribute](http://msdn.microsoft.com/en-us/library/84c42s56.aspx)可用于执行此操作。我们使用它来执行一个系统值到另一个系统值的映射(即Enum值代表一个系统的值,并且我们有几个描述属性用于映射到其他系统,或者更好的描述,或者需要耦合的一些其他相关信息与枚举值)。 – 2013-10-25 06:01:09