我必须调用以下方法:
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,所以它不可用。
最佳答案
假设我有以下结构:
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
我从方法中获取参数类型,然后从该类型中获取枚举值。
关于c# - 如何通过反射调用带有枚举(enum)参数的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22417208/