【问题标题】:c# string to enum mapping [duplicate]c#字符串到枚举映射[重复]
【发布时间】:2014-05-14 09:29:20
【问题描述】:

我有以下枚举:

public enum ItemType
{
   Foo =0,
   Bar =1
}

然后是传递给方法的小写字符串。

如何将字符串与我的枚举进行比较并返回枚举。

public ItemType Method(string value)
{
   ///compare string to enum here and return Enum
} 

并且该方法像这样接收值作为参数(注意小写)

string value = "foo";  /// or value ="bar"

ItemType type = Method(value)

【问题讨论】:

    标签: c# enums


    【解决方案1】:

    您正在寻找Enum.TryParse 方法。

    public ItemType Method(string value)
    {
        ItemType item;
        if(Enum.TryParse(value, true, out item)) return item;
    
        else /* throw exception or return defaul value  */
    }
    

    第二个参数是允许您执行不区分大小写的搜索。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-11
      • 2021-11-09
      • 2019-01-29
      • 2012-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多