【问题标题】:Getting Unhandled Exception: System.Reflection.TargetParameterCountException: Parameter count mismatch获得未处理的异常:System.Reflection.TargetParameterCountException:参数计数不匹配
【发布时间】:2018-02-24 11:37:31
【问题描述】:

我收到参数计数不匹配异常:

获取未处理的异常: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();
        }
    }

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    问题在这里:

    string customerObject = (string)method.Invoke(customerInstance, obj);
    

    ...以及方法:

    public string printCustomerDetails(object[] parameters)
    

    这个MethodInfo.Invoke(...)重载的输入参数(第二个)参数是一个参数数组,你的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
    • 感谢您的建议,我将其更改为 List CustomerList = new List() { "Robinson", "attison", "Todd" };对象[] obj = (object[])CustomerList.ToArray();
    猜你喜欢
    • 1970-01-01
    • 2016-09-21
    • 2011-12-04
    • 1970-01-01
    • 2011-11-17
    • 2021-01-03
    • 2023-03-11
    • 2018-02-14
    • 1970-01-01
    相关资源
    最近更新 更多