gpt4 book ai didi

c# - 反射调用方法 - 参数异常

转载 作者:太空宇宙 更新时间:2023-11-03 19:57:53 25 4
gpt4 key购买 nike

我有一个 Dictionary<string, object>为了我的命令。所有命令都有一个从 Cmd 类扩展而来的类。现在我尝试调用 OnExecute方法,但我得到一个 ArgumentException .

这是我调用方法的函数:

public void Execute(string command, string[] args)
{
try {
Type type = commands[command].GetType();
MethodInfo method = type.GetMethod("OnExecute");
method.Invoke(commands[command], args);
}
catch (ArgumentException ex)
{
Program.Exception(ex);
} catch (TargetException ex)
{
Program.Exception(ex);
}
}

这是我的 Cmd 类

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Valda.Valda.Command
{
public class Cmd
{

public Cmd()
{

}

public void OnExecute(string[] args)
{
Program.WriteLine(args.ToString());
}
}
}

最佳答案

由于您的方法采用一个参数 (OnExecute(string[] args)),该参数是字符串数组,因此您需要传递具有 string[] 类型的单个元素的数组至 Invoke方法:

 method.Invoke(commands[command], new object[] {args});

关于c# - 反射调用方法 - 参数异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31507687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com