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

标签 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,所以它不可用。

最佳答案

假设我有以下结构:

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/

相关文章:

c# - 使用 OpenCV(C#、emgu cv)检测屏幕上的输入文本字段

c# - EF Core 到 Mysql 表绑定(bind)

c# - SetWindowsHookEx 不适用于线程 ID

Python 的 getattr 被调用了两次?

.net - 我可以在 .Net 3.5 项目中使用任务并行库吗?

c# - 触发事件时的事件和委托(delegate)顺序

java - 如何访问我只通过字符串名称知道的类的类字段?

c# - 如何只获取可以复制的文件?

wpf - MVVM WPF 组合框 : creating a template for comboboxitem

C# 查找同一层次结构的两种类型共享的属性