使用反射从库中调用方法

时间:2013-11-08 03:33:52

标签: c# .net

如何从dll调用方法?我正在尝试创建一个可以从我的静态控制台应用程序调用的菜单。运行此代码时出现错误Object reference not set to an instance of an object.错误。

public class Menu
{
    public string Title;
    public Type Program;
    public Dictionary<int, Tuple<string, MethodInfo>> Choices;

    public Menu(Type program, string title, string[,] choices)
    {
        Program = program;
        Title = title;
        Choices =
            new Dictionary<int, Tuple<string, MethodInfo>>();
        for (int i = 0; i < choices.GetLength(0); i++)
        {
            Choices.Add(i,
                        new Tuple<string, MethodInfo>(choices[i, 0], program.GetMethod(choices[i, 1])));
        }
    }

    public void Create()
    {
        Console.WriteLine(Title);
        for (int i = 0; i < Choices.Count; i++)
            Console.WriteLine("{0}: {1}", i, Choices[i].Item1);
        int choice = ConsoleInput.GetNumber();
        while (choice < Choices.Count - 1)
            Choices[choice].Item2.Invoke(null, null);
    }
}

实例化

调用的两个方法返回void。

static readonly string[,] MainMenuChoices = new[,] {
    {"Invoke Testing", "InvokeTesting()"},
    {"Invoke Test","InvokeTest()"}
};

static readonly Menu MainMenu = new Menu(typeof(Program), "Menu Test", MainMenuChoices);

0 个答案:

没有答案