programing tip

Enum에서 문자열을 검색하고 Enum을 반환

itbloger 2020. 6. 13. 10:24
반응형

Enum에서 문자열을 검색하고 Enum을 반환


열거 형이 있습니다.

public enum MyColours
{
    Red,
    Green,
    Blue,
    Yellow,
    Fuchsia,
    Aqua,
    Orange
}

그리고 나는 문자열이 있습니다 :

string colour = "Red";

돌아올 수 있기를 원합니다.

MyColours.Red

에서:

public MyColours GetColour(string colour)

지금까지 나는 가지고있다 :

public MyColours GetColours(string colour)
{
    string[] colours = Enum.GetNames(typeof(MyColours));
    int[]    values  = Enum.GetValues(typeof(MyColours));
    int i;
    for(int i = 0; i < colours.Length; i++)
    {
        if(colour.Equals(colours[i], StringComparison.Ordinal)
            break;
    }
    int value = values[i];
    // I know all the information about the matched enumeration
    // but how do i convert this information into returning a
    // MyColour enumeration?
}

보시다시피, 나는 조금 붙어 있습니다. 어쨌든 값으로 열거자를 선택할 수 있습니까? 다음과 같은 것 :

MyColour(2) 

결과

MyColour.Green

System.Enum.Parse를 확인하십시오.


enum Colors {Red, Green, Blue}

// your code:
Colors color = (Colors)System.Enum.Parse(typeof(Colors), "Green");


int를 열거 형으로 캐스팅 할 수 있습니다

(MyColour)2

Enum.Parse 옵션도 있습니다.

(MyColour)Enum.Parse(typeof(MyColour), "Red")

.NET (+ Core) 및 C # 7에 대한 최신 변경 사항을 감안할 때 가장 좋은 솔루션은 다음과 같습니다.

var ignoreCase = true;
Enum.TryParse("red", ignoreCase , out MyColours colour);

색상 변수는 Enum의 범위 내에서 사용될 수 있습니다.


당신이 필요하다 Enum.Parse .


OregonGhost의 답변 +1을 표시 한 다음 반복을 사용하려고 시도했지만 Enum.GetNames가 문자열을 반환하기 때문에 그것이 옳지 않다는 것을 깨달았습니다. Enum.GetValues를 원합니다.

public MyColours GetColours(string colour)
{  
   foreach (MyColours mc in Enum.GetValues(typeof(MyColours))) 
   if (mc.ToString() == surveySystem) 
      return mc;

   return MyColors.Default;
}

You can use Enum.Parse to get an enum value from the name. You can iterate over all values with Enum.GetNames, and you can just cast an int to an enum to get the enum value from the int value.

Like this, for example:

public MyColours GetColours(string colour)
{
    foreach (MyColours mc in Enum.GetNames(typeof(MyColours))) {
        if (mc.ToString().Contains(colour)) {
            return mc;
        }
    }
    return MyColours.Red; // Default value
}

or:

public MyColours GetColours(string colour)
{
    return (MyColours)Enum.Parse(typeof(MyColours), colour, true); // true = ignoreCase
}

The latter will throw an ArgumentException if the value is not found, you may want to catch it inside the function and return the default value.


As mentioned in previous answers, you can cast directly to the underlying datatype (int -> enum type) or parse (string -> enum type).

but beware - there is no .TryParse for enums, so you WILL need a try/catch block around the parse to catch failures.


You might also want to check out some of the suggestions in this blog post: My new little friend, Enum<T>

The post describes a way to create a very simple generic helper class which enables you to avoid the ugly casting syntax inherent with Enum.Parse - instead you end up writing something like this in your code:

MyColours colour = Enum<MyColours>.Parse(stringValue); 

Or check out some of the comments in the same post which talk about using an extension method to achieve similar.


class EnumStringToInt // to search for a string in enum
{
    enum Numbers{one,two,hree};
    static void Main()
    {
        Numbers num = Numbers.one; // converting enum to string
        string str = num.ToString();
        //Console.WriteLine(str);
        string str1 = "four";
        string[] getnames = (string[])Enum.GetNames(typeof(Numbers));
        int[] getnum = (int[])Enum.GetValues(typeof(Numbers));
        try
        {
            for (int i = 0; i <= getnum.Length; i++)
            {
                if (str1.Equals(getnames[i]))
                {
                    Numbers num1 = (Numbers)Enum.Parse(typeof(Numbers), str1);
                    Console.WriteLine("string found:{0}", num1);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Value not found!", ex);
        }
    }
}

One thing that might be useful to you (besides the already valid/good answers provided so far) is the StringEnum idea provided here

With this you can define your enumerations as classes (the examples are in vb.net):

< StringEnumRegisteredOnly(), DebuggerStepThrough(), ImmutableObject(True)> Public NotInheritable Class eAuthenticationMethod Inherits StringEnumBase(Of eAuthenticationMethod)

Private Sub New(ByVal StrValue As String)
  MyBase.New(StrValue)   
End Sub

< Description("Use User Password Authentication")> Public Shared ReadOnly UsernamePassword As New eAuthenticationMethod("UP")   

< Description("Use Windows Authentication")> Public Shared ReadOnly WindowsAuthentication As New eAuthenticationMethod("W")   

End Class

And now you could use the this class as you would use an enum: eAuthenticationMethod.WindowsAuthentication and this would be essentially like assigning the 'W' the logical value of WindowsAuthentication (inside the enum) and if you were to view this value from a properties window (or something else that uses the System.ComponentModel.Description property) you would get "Use Windows Authentication".

I've been using this for a long time now and it makes the code more clear in intent.


(MyColours)Enum.Parse(typeof(MyColours), "red", true); // MyColours.Red
(int)((MyColours)Enum.Parse(typeof(MyColours), "red", true)); // 0

var color =  Enum.Parse<Colors>("Green");

참고URL : https://stackoverflow.com/questions/2290262/search-for-a-string-in-enum-and-return-the-enum

반응형