简体   繁体   English

按类型调用泛型方法

[英]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? 如何将结果转换为用于调用DoSomething方法的类型 And how simpler to call generic method using type variable? 使用类型变量调用泛型方法更简单吗?

How to convert result to type for call DoSomething method? 如何将结果转换为用于调用DoSomething方法的类型?

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: 做到这一点在.NET 4.0和更高版本的一种方法是使用dynamic的,而不是objectresult ,就像这样:

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. 只有在100%确定DoSomething()方法将在运行时存在的情况下,您才能这样做。 Otherwise, there is going to be an exception at runtime, which you would need to catch and process. 否则,在运行时将出现异常,您需要捕获并处理该异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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