如何通过反射调用带枚举(enum)参数的方法?

时间:2014-03-14 22:54:26

标签: c# reflection .net-3.5 c#-3.0

我必须调用以下方法:

public bool Push(button RemoteButtons)

RemoteButtons以这种方式定义:

enum RemoteButtons { Play, Pause, Stop }

Push方法属于RemoteControl类。 RemoteControl类和RemoteButton枚举都位于我需要在运行时加载的程序集内。我能够加载程序集并以这种方式创建RemoteControl实例:

Assembly asm = Assembly.LoadFrom(dllPath);
Type remoteControlType = asm.GetType("RemoteControl");
object remote = Activator.CreateInstance(remoteControlType);

现在,我如何调用Push方法,知道它的唯一参数是一个枚举,我还需要在运行时加载?

如果我在C#4上,我会使用dynamic对象,但我使用的是C#3 / .NET 3.5,因此它不可用。

2 个答案:

答案 0 :(得分:4)

假设我有以下结构:

public enum RemoteButtons
{
    Play,
    Pause,
    Stop
}
public class RemoteControl
{
    public bool Push(RemoteButtons button)
    {
        Console.WriteLine(button.ToString());
        return true;
    }
}

然后我可以使用反射来获取像这样的值:

Assembly asm = Assembly.GetExecutingAssembly();
Type remoteControlType = asm.GetType("WindowsFormsApplication1.RemoteControl");
object remote = Activator.CreateInstance(remoteControlType);

var methodInfo = remoteControlType.GetMethod("Push");
var remoteButtons = methodInfo.GetParameters()[0];

// .Net 4.0    
// var enumVals = remoteButtons.ParameterType.GetEnumValues();

// .Net 3.5
var enumVals = Enum.GetValues(remoteButtons.ParameterType);

methodInfo.Invoke(remote, new object[] { enumVals.GetValue(0) });   //Play
methodInfo.Invoke(remote, new object[] { enumVals.GetValue(1) }); //Pause
methodInfo.Invoke(remote, new object[] { enumVals.GetValue(2) }); //Stop

我从方法中获取参数类型,然后从该类型获取枚举值。

答案 1 :(得分:1)

以下代码可以正常工作!

asm = Assembly.LoadFrom(dllPath);
Type typeClass = asm.GetType("RemoteControl");
obj = System.Activator.CreateInstance(typeClass);
Type[] types = asm.GetTypes();
Type TEnum = types.Where(d => d.Name == "RemoteButtons").FirstOrDefault();
MethodInfo method = typeClass.GetMethod("Push", new Type[] { TEnum});
object[] parameters = new object[] { RemoteButtons.Play };
method.Invoke(obj, parameters);

请注意以下代码:“ Type TEnum = types.Where(d => d.Name == "RemoteButtons").FirstOrDefault();” 您必须使用此代码从Assembly中获取Type。

但不直接使用typeof(RemoteButtons)查找类似这样的方法:“ MethodInfo method = typeClass.GetMethod("Push", new Type[] { typeof(RemoteButtons) });”这实际上不是SAME类型。

相关问题