How to call static universal methods of a class if parameters of type type are unknown before execution?

Suppose I have a static generic class. Its general type parameters are not available until executed. How to call your members?

See the following code snippet:

static class Utility<T>
{
    public static void DoSomething() { }
}   

class Tester
{
    static Type GetTypeAtRuntime()
    {
      // return an object of type Type at runtime.
    } 
    static void Main(string[] args)
    {


        Type t = GetTypeAtRuntime();

        // I want to invoke Utility<>.DoSomething() here. How to do this?

    }
}

Edit:

OK, this is a solution based on the answers given by the two guys below. Thanks to both of you!

 static class Utility<T>
{
    //Trivial method
    public static void DoSomething(T t) { Console.WriteLine(t.GetType()); }
}

// assume Foo is unknown at compile time.
class Foo { }

class Tester
{

    static void Main(string[] args)
    {

        Type t = typeof(Foo);// assume Foo is unknown at compile time.

        Type genType = typeof(Utility<>);

        Type con = genType.MakeGenericType(new Type[] { t });

        MethodInfo mi = con.GetMethod("DoSomething", BindingFlags.Static | BindingFlags.Public);

        mi.Invoke(null, new object[] { Activator.CreateInstance(t) });

    }
}
+1
source share
2 answers

Then you will need to use reflection to get the method and call it. Arguments of a general type must be allowed to compile time if you intend to declare an object of this type:

Type t= GetTypeAtRuntime();;
var doSomething = typeof(List<>).MakeGenericType(t).GetMethod("DoSomething", BindingFlags.Static | BindingFlags.Public);
doSomething.Invoke(null, new object[] { });

However, in your example, T is not used in the signature or implementation of the method, and if in this case I would move it to a non-generic base class.

: , , , mpore, . static/generic

+2

MakeGenericType , . ,

static void Main(string[] args)
    {
        Type t = GetTypeAtRuntime();
        Type genType = typeof(Utility<>);
        Type constructed = genType.MakeGenericType(new Type[] { t });

        // Now use reflection to invoke the method on constructed type
        MethodInfo mi = constructed.GetMethod("DoSomething", BindingFlags.Static);
        mi.Invoke(null, null);
+2

Source: https://habr.com/ru/post/1606625/


All Articles