developer tip

C # 열거 형에 값 포함

optionbox 2020. 12. 3. 07:46
반응형

C # 열거 형에 값 포함


열거 형이 있습니다

enum myEnum2 { ab, st, top, under, below}

주어진 값이 myEnum에 포함되어 있는지 테스트하는 함수를 작성하고 싶습니다.

그런 것 :

private bool EnumContainValue(Enum myEnum, string myValue)
{
     return Enum.GetValues(typeof(myEnum))
                .ToString().ToUpper().Contains(myValue.ToUpper()); 
}

그러나 myEnum 매개 변수가 인식되지 않기 때문에 작동하지 않습니다.


직접 작성할 필요가 없습니다.

    // Summary:
    //     Returns an indication whether a constant with a specified value exists in
    //     a specified enumeration.
    //
    // Parameters:
    //   enumType:
    //     An enumeration type.
    //
    //   value:
    //     The value or name of a constant in enumType.
    //
    // Returns:
    //     true if a constant in enumType has a value equal to value; otherwise, false.

    public static bool IsDefined(Type enumType, object value);

예:

if (System.Enum.IsDefined(MyEnumType, MyValue))
{
    // Do something
}

사용하지 않는 이유

Enum.IsDefined(typeof(myEnum), value);

BTWEnum<T> 호출을 감싸는 제네릭 클래스 를 만드는 것이 좋습니다 Enum(실제로 이와 같은 것이 Framework 2.0 이상에 추가되지 않은 이유가 궁금합니다).

public static class Enum<T>
{
    public static bool IsDefined(string name)
    {
        return Enum.IsDefined(typeof(T), name);
    }

    public static bool IsDefined(T value)
    {
        return Enum.IsDefined(typeof(T), value);
    }

    public static IEnumerable<T> GetValues()
    {
        return Enum.GetValues(typeof(T)).Cast<T>();
    }
    // etc
}

이렇게하면이 모든 것을 피하고 typeof강력한 형식의 값을 사용할 수 있습니다.

Enum<StringSplitOptions>.IsDefined("None")

이 방법을 사용하십시오

Enum.IsDefined 메서드 -지정된 값을 가진 상수가 지정된 열거에 존재하는지 여부를 표시합니다.

enum myEnum2 { ab, st, top, under, below};
myEnum2 value = myEnum2.ab;
 Console.WriteLine("{0:D} Exists: {1}", 
                        value, myEnum2.IsDefined(typeof(myEnum2), value));

이 경우 ToString ()으로 수행하는 작업은 다음과 같습니다.

Enum.GetValues(typeof(myEnum)).ToString()... 대신 다음과 같이 작성해야합니다.

Enum.GetValues(typeof(myEnum).ToString()...

차이점은 괄호 안에 있습니다 ...


또한 이것을 사용할 수 있습니다.

    enum myEnum2 { ab, st, top, under, below }
    static void Main(string[] args)
    {
        myEnum2 r;
        string name = "ab";
        bool result = Enum.TryParse(name, out r);
    }

The result will contain whether the value is contained in enum or not.


   public static T ConvertToEnum<T>(this string value)
    {
        if (typeof(T).BaseType != typeof(Enum))
        {
            throw new InvalidCastException("The specified object is not an enum.");
        }
        if (Enum.IsDefined(typeof(T), value.ToUpper()) == false)
        {
            throw new InvalidCastException("The parameter value doesn't exist in the specified enum.");
        }
        return (T)Enum.Parse(typeof(T), value.ToUpper());
    }

If your question is like "I have an enum type, enum MyEnum { OneEnumMember, OtherEnumMember }, and I'd like to have a function which tells whether this enum type contains a member with a specific name, then what you're looking for is the System.Enum.IsDefined method:

Enum.IsDefined(typeof(MyEnum), MyEnum.OneEnumMember); //returns true
Enum.IsDefined(typeof(MyEnum), "OtherEnumMember"); //returns true
Enum.IsDefined(typeof(MyEnum), "SomethingDifferent"); //returns false

If your question is like "I have an instance of an enum type, which has Flags attribute, and I'd like to have a function which tells whether this instance contains a specific enum value, then the function looks something like this:

public static bool ContainsValue<TEnum>(this TEnum e, TEnum val) where Enum: struct, IComparable, IFormattable, IConvertible
{
    if (!e.GetType().IsEnum)
        throw new ArgumentException("The type TEnum must be an enum type.", nameof(TEnum));

    dynamic val1 = e, val2 = val;
    return (val1 | val2) == val1;
}

Hope I could help.


Use the correct name of the enum (myEnum2).

Also, if you're testing against a string value you may want to use GetNames instead of GetValues.


just cast the enum as:

string something = (string)myEnum;

and now comparison is easy as you like


I think that you go wrong when using ToString().

Try making a Linq query

private bool EnumContainValue(Enum myEnum, string myValue)
{
    var query = from enumVal in Enum.GetNames(typeof(GM)).ToList()
                       where enumVal == myValue
                       select enumVal;

    return query.Count() == 1;
}

참고URL : https://stackoverflow.com/questions/13248869/c-sharp-enum-contains-value

반응형