How to call a method with an enumerated argument (enum) through reflection?

I need to call the following method:

public bool Push(button RemoteButtons)

RemoteButtons is defined as follows:

enum RemoteButtons { Play, Pause, Stop }

The Push method belongs to the RemoteControl class. Both the RemoteControl class and the RemoteButton enumeration are located inside the assembly that I need to load at runtime. I can load the assembly and create an instance of RemoteControl as follows:

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

Now, how do I call the Push method, knowing that the only argument is an enum, which I also need to load at runtime?

If I were in C # 4, I would use an object dynamic, but I am in C # 3 / .NET 3.5, so it is not available.

+4
source share
1

, :

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

, .

+2

Source: https://habr.com/ru/post/1531868/


All Articles