Вопрос

I have

Enum eNUM
{
     one,Two,Three
}

I have a UserDefinedString . For example: Four I want to check whether user defined string present in eNUm. I tried with

eNUM _num;
if (Enum.TryParse<eNUM>("UserDefinedString", out _num))
{
   //do some thing 
}

I also tried:

if (Enum.IsDefined(typeof(eNUM), "UserDefinedString"))

This is not working for me

Это было полезно?

Решение 3

The first example works:

if (Enum.TryParse<eNUM>("Four", out _num))
{
   //do some thing 
}
else
{
   // invalid enum value
}

When calling this with Four, you will get in the else branch. When calling with Two it works.

If you want to ignore the casing, you can set the second parameter of TryParse to true.

Другие советы

Try

Enum.GetNames(typeof(eNUM));

this will get you all values in the enum as string, then you can check for your key using linq function like Contains or Any

Make sure it is an exact match when trying to parse. You can make life easier by forcing case before comparison if you know your enum only contains lower-case values, for example:

Enum eNUM
{
    one, two, three ...
}

...

eNUM num;
string findThisValue = "OnE"; // Odd casing...
if (Enum.TryParse(findThisValue.ToLower(), out num))
{
    // Do something with num
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top