简体   繁体   English

如何使用反射在私有方法中使用私有枚举?

[英]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() . 尝试typeof(Class1).GetNestedTypes() It should return a list all types that nested into Class1 - like MyEnum is. 它应该返回一个嵌套到Class1中的所有类型的列表 - 就像MyEnum一样。 So look through the list of nested types, find the MyEnum type and pass it to GetMethod. 因此,查看嵌套类型列表,找到MyEnum类型并将其传递给GetMethod。

GetNestedTypes documentation on MSDN: http://msdn.microsoft.com/en-us/library/system.type.getnestedtypes(v=vs.100).aspx MSDN上的GetNestedTypes文档: 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. 还有一个GetNestedType()方法接受类型名称和一些BindingFlags,它允许您按名称搜索特定的嵌套类型。

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: 通过调用GetNestedTypes()方法获取它:

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. 如果您想通过名称或其他内容找到它,请使用不同的lambda。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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