对于某些业务的原因,我不能调用服务的直接方法,所以我写了这样的代码:如何调用(不直接调用)的任务<T> ContinueWith方法?
class TheService {
public Task<string> CallMe(string input) {
return Task.Run(() => {
return "the result of " + input;
});
}
}
//The calling code segment...
//Get the target method's info
MethodInfo mi = typeof(TheService).GetMethod("CallMe");
//Get the target method's return type, yes, it's a Task<string>
ParameterInfo pi = mi.ReturnParameter;
Type taskType = pi.ParameterType;
//Get the service instance.(I new it here for simple reason)
TheService svc = new TheService();
//Invoke the target method and get the Task<string>, however I got only an object (not Task<string>) because I invoke it, not call it directly
object task = mi.Invoke(svc, new[] {"test"});
//How can I make a ContinueWith call here?
//This isn't work! It throws a conversion exception.
//Note: Task<string> is just an example. I wound actually get Task<MyClassA> or Task<MyClassB> here. So, I cannot hard code the conversion. However, I know the Type of Task<T> here. My instinct tells me I should use Invoke again but I don't know how to do.
((Task<object>)task).ContinueWith(a=>{
Console.WriteLine("The result is " + a.Result);
});
我的问题是如何调用该对象的(这实际上是一个任务)ContinueWith方法?
或任何解决方法吗?
什么转换例外居然说? –
他不会静态地知道类型参数将会是什么。 – usr