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