简体   繁体   中英

How to call some method via Reflection without any parameters and any return values?

How to call some method via Reflection without any parameters and any return values?

Here is MSDN sample

// Define a class with a generic method.
public class Example
{
    public static void Generic<T>()
    {
        Console.WriteLine("\r\nHere it is: {0}", "DONE");
    }
}

What should be within typeof(???) then?

MethodInfo miConstructed = mi.MakeGenericMethod(typeof(???));

Thank you!!!

Before being able to invoke a generic method you need to specify its generic argument(s). So you pass the type you want to be used as generic argument:

public class Example
{
    public static void Generic<T>()
    {
        Console.WriteLine("The type of T is: {0}", typeof(T));
    }
}

class Program
{
    static void Main()
    {
        var mi = typeof(Example).GetMethod("Generic");
        MethodInfo miConstructed = mi.MakeGenericMethod(typeof(string));
        miConstructed.Invoke(null, null);
    }
}

which should print:

The type of T is: System.String

If you were invoking that through C#, you would need to supply a type, for example:

Example.Generic<int>();

that requirement does not change; simply, that line would become:

mi.MakeGenericMethod(typeof(int)).Invoke(null, null);

For a complete, working illustration:

class Example
{
    public static void Generic<T>()
    {
        System.Console.WriteLine("\r\nHere it is: {0}", "DONE");
    }
    static void Main()
    {
        var mi = typeof (Example).GetMethod("Generic");
        mi.MakeGenericMethod(typeof(int)).Invoke(null, null);
    }
}

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