Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting MemberInfo[] to Enum

I've been searching for a while but didn't find the solutions. I have an assembly in a GAC. I have to to load it using reflection. After that I need to get and address to Enum. But instead I can just get MemberInfo[]. I don't understand how to convert MemberInfo[] to Enum.

I have code like this:

//test assembly contains 
public class MyClass
{
    public enum MyEnum 
    {
        MyVavue, 
        MyValue2
    }
}

Assembly s = Assembly.Load("test");
Type type = s.GetTypes()[1];
MemberInfo[] memberInfos = type.GetMembers(
    BindingFlags.Public | 
    BindingFlags.Static);

//I need to convert memberInfos to MyEnum
//and after that receive ---> MyEnum.MyValue <---  
like image 683
Alexandr Avatar asked May 26 '12 07:05

Alexandr


People also ask

How to convert a string to a enum?

Use the Enum. IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.

How to convert to enum in c#?

To convert string to enum use static method Enum. Parse. Parameters of this method are enum type, the string value and optionally indicator to ignore case.

How to get enum value based on string in c#?

To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

How do I override strings in enum?

Since Enum in Java allows a programmer to override an inherited method and since Enum has access to all Object class methods, you can easily override the toString() method to provide a custom String implementation for an Enum instance which can further use to convert that Enum instance to String in Java.


2 Answers

Use GetFields instead of GetMembers and then call GetValue(null) to get the enum value.

like image 72
Lucero Avatar answered Sep 27 '22 17:09

Lucero


You should simply use Enum.GetValues. That's exactly what it does - use reflection to get the enum fields:

Assembly s = Assembly.Load("test");
Type type = s.GetTypes()[1];
object[] values = Enum.GetValues(type);
object myValue = values.First(v => v.ToString() == "MyValue");
like image 41
Eli Arbel Avatar answered Sep 27 '22 16:09

Eli Arbel