简体   繁体   中英

Call generic method by type

I have these classes:

public static class A{
    ...
   public C Run<T>(string something)
   {
       ...
   }
}

public static class B{
    ...
    public void Exec<T>(Type type)
    {
        MethodInfo method = typeof(A).GetMethod("Run");
        MethodInfo generic = method.MakeGenericMethod(type);
        var result = generic.Invoke(null, new object[] { "just a string" });
        // bad call in next line
        result.DoSomething();
    }
}


public class C{
    ...
    public void DoSomething(){}
}

How to convert result to type for call DoSomething method? And how simpler to call generic method using type variable?

How to convert result to type for call DoSomething method?

You cannot do that statically, because your code does not know the type at compile time, and the object is already of the correct type. One way to do it in .NET 4.0 and later is to use dynamic instead of object for the result , like this:

dynamic result = generic.Invoke(null, new object[] { "just a string" });
result.DoSomething(); // This will compile

You can do it like this only if you are 100% certain that the DoSomething() method is going to be there at runtime. Otherwise, there is going to be an exception at runtime, which you would need to catch and process.

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