简体   繁体   中英

How to use a private enum in a private method using reflection?

I got an internal method where one of the input parameter is an internal Enum. How do I get a enum value and pass it to the method?

Example:

internal enum MyEnum
{
    One,
    Two,
    Three
}


internal int InternalTest(string test, MyEnum enumTest)
{
    return test.Length;
}

And then obtained by something like this:

MethodInfo addInternal = typeof(Class1).GetMethod("InternalTest", BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(string), typeof(?????) }, null);

Thanks!

Ivar

If it is in a different assembly, then getting the type would have to be by name, for example;

Type type = assembly.GetType("SomeNamespace.SomeType+SomeNestedType");

Which might be (from the example):

Type type = typeof(Class1).Assembly.GetType("Class1+MyEnum");

A more interesting question is: how to get a value (boxed to the correct type) for the enum - you need something like:

object val = Enum.ToObject(type, 123);

Try typeof(Class1).GetNestedTypes() . It should return a list all types that nested into Class1 - like MyEnum is. So look through the list of nested types, find the MyEnum type and pass it to GetMethod.

GetNestedTypes documentation on MSDN: http://msdn.microsoft.com/en-us/library/system.type.getnestedtypes(v=vs.100).aspx

There is also a GetNestedType() method that accepts a type name and some BindingFlags which allows you to search for specific nested type by name.

To get a value of the enum using reflection, use this:

object enumValue = myEnumType.GetField("ValueName", BindingFlags.Static | BindingFlags.Public);

Get it by calling the GetNestedTypes() method:

Type type = typeof(Program).GetNestedTypes().FirstOrDefault(x => x.IsEnum);

This will return the (arbitrary) enum in the type. If you want to find it by name or something, use a different lambda.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM