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 <---
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.
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.
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.
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.
Use GetFields
instead of GetMembers
and then call GetValue(null)
to get the enum value.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With