开发者

Is there a Case invariant way to compare string with a Enum in Enum.IsDefined / Enum.Parse

开发者 https://www.devze.com 2023-04-07 01:00 出处:网络
So if you don\'t have access to an Enum or control over a string that is to be compared with enum values, is there a better or cleaner way than the below code to get the value of the Enum that matches

So if you don't have access to an Enum or control over a string that is to be compared with enum values, is there a better or cleaner way than the below code to get the value of the Enum that matches and use it in a call to:

 Enum.IsDefined() or 
 Enum.Parse()

Example:

  var enumValues = Enum.GetValues(typeof(someType));

  foreach (var value in enumValues) {
        if (value.ToString().ToLowerInvariant() 开发者_运维技巧== stringToCompare.ToLowerInvariant()) {
                stringToCompare = value.ToString();
        }
  }

Which at this point if there was a match you would have the correct enum value that you could then use in either (Enum.IsDefinied() or Enum.Parse())

Is there a better way than what I defined?


someType varName = Enum.Parse(typeof(someType), stringToCompare, true);

Using this overload of enum.Parse()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号