[英]Store Generic Type Parameter for Further Use
有什么方法可以存储泛型类型参数以备将来使用。 场景就是这样。
Queue<ApiHandlerHelper> requestQueue = new Queue<ApiHandlerHelper> ();
public void HitApi<T> (ApiHandlerHelper helper)
{
if (_IfHandlerProcessing) {
requestQueue.Enqueue (helper);
} else {
StartCoroutine (checkInternetConnection<T> ());
_IfHandlerProcessing = true;
}
}
HitApi收到来自多个管理者的呼叫,我想检查Hitpi是否正在忙于处理一个管理者的请求,即将到来的请求将进入队列。 现在,我需要存储通用类型参数“ T”,以便在以后的阶段中使用。 像这样的东西
AoiHandlerObject.StoreGenerticType<T> ();
我需要存储T类型,以便在我们收到前任经理的回复时可以自动调用HitApi。
您不能存储泛型类型参数,但是可以对泛型参数进行存储 。 虽然您将无法在编译期间提供泛型参数类型,但可以使用反射调用泛型方法(或实例化泛型类型):
Type genericArg1 = typeof(T);
现在应该使用反射调用您的方法:
// obj.HitApi<T>(ApiHandlerHelper helper)
typeof(ClassContainingHitApiMethod)
.GetMethod("HitApi", BindingFlags.Public | BindingFlags.Instance)
.MakeGenericMethod(genericArg1)
.Invoke(instanceOfClassContainingHitApiMethod, new object[] { instanceOfApiHelper });
使用typeof(T)
检索表示传递给T
参数的类型的Type
实例。 然后,您可以像其他对象引用一样存储此Type
实例以供进一步使用。
如果要存储Type
的实例,并存储T
的类型,则可以使用typeof(T)
。
var type = typeof(T);
StoreType(type);
但是从变量 T
获取HitApi<T>
可能很麻烦,因为它需要一些反思。 我认为实际上存储typeof(HitApi<T>)
可能会少一些工作,具体取决于您的确切需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.