Chr*_*isB 5 c# reflection .net-3.5 c#-3.0
我必须调用以下方法:
public bool Push(button RemoteButtons)
Run Code Online (Sandbox Code Playgroud)
RemoteButtons以这种方式定义:
enum RemoteButtons { Play, Pause, Stop }
Run Code Online (Sandbox Code Playgroud)
Push方法属于RemoteControl类.RemoteControl类和RemoteButton枚举都位于我需要在运行时加载的程序集内.我能够加载程序集并以这种方式创建RemoteControl实例:
Assembly asm = Assembly.LoadFrom(dllPath);
Type remoteControlType = asm.GetType("RemoteControl");
object remote = Activator.CreateInstance(remoteControlType);
Run Code Online (Sandbox Code Playgroud)
现在,我如何调用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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我可以使用反射来获取如下值:
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
Run Code Online (Sandbox Code Playgroud)
我从方法中获取参数类型,然后从该类型获取枚举值。
| 归档时间: |
|
| 查看次数: |
2523 次 |
| 最近记录: |