简体   繁体   中英

C# Cannot convert from 'System.DateTime' to 'object[]' methodinfo.invoke

Look I maybe approaching this the wrong way and direction is more than welcome.

I'm trying to trigger all the Start methods in my solution.

The Start method takes a datetime

However when trying to pass the date as a parameter of "Invoke" I run into the error

cannot convert from System.DateTime to object[]

Any thoughts welcome

Thanks 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);
}

The second parameter of method Invoke expects an object array with your parameters. So instead of passing a DateTime wrap it in object arrray:

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

You are passing as parameter a DateTime when the expected parameter is an array of objects.

Try the following:

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 });
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM