C#: 无法将 'System.DateTime' 转换为 'object[]':methodinfo.invoke

3

我可能是错误的方法,欢迎更正。

我正在尝试触发我的解决方案中的所有Start方法。

Start方法需要一个日期参数。

然而,当我尝试将日期作为“Invoke”的参数传递时,我遇到了错误:

无法将System.DateTime转换为对象[]

欢迎任何想法。

谢谢 gws

scheduleDate = new DateTime(2010, 03, 11);

Type[] typelist = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "AssetConsultants");

foreach (Type t in typelist)
{
    var methodInfo = t.GetMethod("Start", new Type[] {typeof(DateTime)} );
    if (methodInfo == null) // the method doesn't exist
    {
       // throw some exception
    }

    var o = Activator.CreateInstance(t);                 
    methodInfo.Invoke(o, scheduleDate);
}

2个回答

9
方法Invoke的第二个参数要求您传递包含参数的对象数组。因此,不要直接传递DateTime,而应该将其封装在对象数组中:
methodInfo.Invoke(o, new object[] { scheduleDate });

0

您正在将一个 DateTime 作为参数传递,但期望的参数是一个对象数组。

请尝试以下操作:

private void button_Click(object sender, EventArgs e)
    {
        var scheduleDate = new DateTime(2010, 03, 11);

        var typelist = System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
                  .Where(t => t.Namespace == "AssetConsultants")
                  .ToList();


        foreach (Type t in typelist)
        {
            var methodInfo = t.GetMethod("Start", new Type[] { typeof(DateTime) });
            if (methodInfo == null) // the method doesn't exist
            {
                // throw some exception
            }

            var o = Activator.CreateInstance(t);

            methodInfo.Invoke(o, new object[] { scheduleDate });
        }

    }

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