存储泛型类型参数以供以后使用



是否有办法存储泛型类型参数以供以后使用?场景是这样的

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类型,以便当我们收到前一个manager的响应时可以自动调用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>),而不是,这取决于你的确切需求是什么。

最新更新