出现未处理的异常:System.Reflection.TargetParameterCountException:参数数量不匹配。

5

我遇到了参数数量不匹配的异常:

遇到未处理的异常:System.Reflection.TargetParameterCountException: 参数计数不匹配。

代码:

class Program
    {
        public static void Main()
        {
            ArrayList CustomerList = new ArrayList();
            CustomerList.Add("Robinson");
            CustomerList.Add("Pattison");
            CustomerList.Add("Todd");

            object[] obj = (object[])CustomerList.ToArray(typeof(object));
            Assembly executingAssembly = Assembly.GetExecutingAssembly();
            Type customerType = executingAssembly.GetType("LateBinding.Customer");
            object customerInstance = Activator.CreateInstance(customerType);
            MethodInfo method = customerType.GetMethod("printCustomerDetails");
            string customerObject = (string)method.Invoke(customerInstance, obj);
            Console.WriteLine("Value is : {0}", customerObject);
        }
    }
    public class Customer
    {
        public string printCustomerDetails(object[] parameters)
        {
            string CustomerName = "";
            foreach (object customer in parameters)
            {
                CustomerName = CustomerName + " " + customer;
            }
            return CustomerName.Trim();
        }
    }
1个回答

9
问题在这里:
string customerObject = (string)method.Invoke(customerInstance, obj);

...以及该方法:

public string printCustomerDetails(object[] parameters)

这个 MethodInfo.Invoke(...) 重载方法的第二个输入参数(second)是一个参数数组,而你的 printCustomerDetails 方法只有一个参数,它是由对象 object[] 组成的数组,所以您需要这样调用 Invoke
method.Invoke(customerInstance, new [] { obj });

关于ArrayList的建议已过时

不要使用ArrayList,它来自.NET 1.x的时代。自从.NET 2.0以后,你需要使用来自System.Collections.Generic命名空间的泛型集合(例如List<T>, HashSet<T>, Queue<T>等)。

如果你需要动态创建数组,我建议你使用List<object>而不是过时的ArrayList,以获得完整的LINQ和LINQ扩展方法支持,以及其他新型泛型列表的改进,自从.NET 2.0(旧日子啊!现在我们处于.NET 4.5)。


@BhuwanPandey 请查看我的关于ArrayList的建议;P - Matías Fidemraizer
谢谢您的建议,我会将其更改为以下代码: List<string> CustomerList = new List<string>() { "Robinson", "attison", "Todd" }; object[] obj = (object[])CustomerList.ToArray(); - Bhuwan Pandey
@MatíasFidemraizer,你的回答解决了我多小时一直在尝试解决的问题。我读了很多文章和答案,但都没有解决我的问题。非常感谢你。 - Syed Irfan Ahmad
@SyedIrfanAhmad 太好了!我很高兴它解决了你的问题!:-D - Matías Fidemraizer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接