2014-06-29 104 views
1

我有这些类:调用泛型方法的类型

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(){} 
} 

如何转换结果呼叫DoSomething的方法类型?而使用类型变量调用泛型方法有多简单?

回答

1

如何将结果转换为类型调用DoSomething方法?

由于代码在编译时不知道类型,并且对象已经是正确的类型,所以不能做到这一点。做到这一点在.NET 4.0和更高版本的一种方法是使用dynamic,而不是objectresult,就像这样:

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

你可以像下面这样做只是如果你是100%肯定,DoSomething()方法将在运行时在那里。否则,运行时会出现异常,您需要捕获并处理这些异常。

+0

好。使用'dynamic'是唯一的方法 –