[英]How to cast object type to Task<T> type?
How can I cast an object instance of type object
to type Task<T>
?我怎样才能投类型的对象实例
object
输入Task<T>
I store a Task<T>
reference in a variable of type object
and need to cast it back to Task<T>
because the method needs to return type Task<T>
.我将
Task<T>
引用存储在类型为object
的变量中,并且需要将其强制转换回Task<T>
因为该方法需要返回类型Task<T>
。
Try using the Task.FromResult<TResult> method
.尝试使用
Task.FromResult<TResult> method
。 From MSDN:来自 MSDN:
T obj = new T();
Task<T> a = Task.FromResult(obj);
If T
is known at the time of casting, there should be no problem doing:如果在铸造时
T
是已知的,那么执行以下操作应该没有问题:
Task<T> myTask = (Task<T>)myObject;
Example: https://dotnetfiddle.net/oOg4E8示例: https : //dotnetfiddle.net/oOg4E8
You can use the as
operator.您可以使用
as
运算符。 If the object is of type Task<T>
you get a correct references.如果对象是
Task<T>
类型,您将获得正确的引用。 Otherwise you get null
.否则你会得到
null
。
var task = obj as Task<T>;
If the object you have stored is actually the Task<T>
you can just use a direct cast.如果您存储的对象实际上是
Task<T>
您可以使用直接转换。
var task = (Task<X>)obj;
If you have the object result, unwrapped, and you need a task result from the instance, you can use Task.FromResult(X)
which return a completed Task<T>
of type X
.如果您有对象结果,展开,并且您需要来自实例的任务结果,您可以使用
Task.FromResult(X)
它返回一个已完成的Task<T>
类型X
。
Given:鉴于:
object
object
Task<T1>
Task<T1>
T1
is not available at compile time. T1
在编译时不可用。Task<T2>
where T1 : T2
, but not T1 == T2
(likely T2
is an interface implemented by T1
).Task<T2>
,其中T1 : T2
,但不是T1 == T2
(可能T2
是由T1
实现的接口)。 The other answers will not work when T1 != T2
.当
T1 != T2
时,其他答案将不起作用。
This extension method works well for me to preform the cast.这种扩展方法很适合我预制演员表。
public static class TaskExtensions
{
public static Task<T> CastTask<T>(this object taskObj)
{
var taskType = taskObj.GetType();
if (!taskType.IsSubClassOfGeneric(typeof(Task<>)))
throw new ArgumentException($"{taskType.FullName} is not of type Task<>");
var resultType = taskType.GenericTypeArguments.First();
var castTaskMethodGeneric = typeof(TaskExtensions)
.GetMethod("CastTaskInner", BindingFlags.Static | BindingFlags.Public);
var castTaskMethod = castTaskMethodGeneric.MakeGenericMethod(
new Type[] { resultType, typeof(T) });
var objCastTask = castTaskMethod.Invoke(null, new object[] { taskObj });
return objCastTask as Task<T>;
}
public static async Task<TResult> CastTaskInner<T, TResult>(Task<T> task)
{
var t = await task;
var tObj = (object)t;
return (TResult)tObj;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.