對於某些業務的原因,我不能調用服務的直接方法,所以我寫了這樣的代碼:如何調用(不直接調用)的任務<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