C# 存储泛型类型参数以供进一步使用

C# 存储泛型类型参数以供进一步使用,c#,generics,c#-4.0,C#,Generics,C# 4.0,是否有任何方法存储泛型类型参数以供进一步使用。 情况就是这样 Queue<ApiHandlerHelper> requestQueue = new Queue<ApiHandlerHelper> (); public void HitApi<T> (ApiHandlerHelper helper) { if (_IfHandlerProcessing) { requestQueue.Enqueue (helpe

是否有任何方法存储泛型类型参数以供进一步使用。 情况就是这样

Queue<ApiHandlerHelper> requestQueue = new Queue<ApiHandlerHelper> ();

public void HitApi<T> (ApiHandlerHelper helper)
    {
        if (_IfHandlerProcessing) {
            requestQueue.Enqueue (helper);
        } else {
            StartCoroutine (checkInternetConnection<T> ());
            _IfHandlerProcessing = true;
        }
    }
Queue requestQueue=new Queue();
公共无效HitApi(ApiHandlerHelper)
{
如果(_IfHandlerProcessing){
requestQueue.Enqueue(helper);
}否则{
启动例行程序(检查InternetConnection());
_IfHandlerProcessing=true;
}
}
HitApi收到来自多个管理器的调用,我想检查Hitpi是否正在忙于处理一个管理器的请求。即将到来的请求将进入队列。现在我需要存储泛型类型参数“T”,以便在以后的阶段中使用。像这样的

AoiHandlerObject.StoreGenerticType<T> ();
AoiHandlerObject.StoreGenericType();

我需要存储T类型,这样当我们收到前一个管理器的响应时,可以自动调用HitApi

使用
typeof(T)
检索表示传递给
T
参数的类型的实例。然后,您可以像任何其他对象引用一样存储此
Type
实例以供进一步使用。

如果要存储类型
Type
的实例,存储类型
T
,则可以使用
typeof(T)


但是从变量
T
获取
HitApi
可能会很麻烦,因为它需要一些反射。我认为存储
typeof(HitApi)
实际上可能会少一些工作,这取决于您的具体需求。

您不能存储泛型类型参数,但可以为泛型参数存储。虽然在编译时无法提供泛型参数类型,但可以使用反射调用泛型方法(或实例化泛型类型):

现在应该使用反射调用您的方法:

// obj.HitApi<T>(ApiHandlerHelper helper)
typeof(ClassContainingHitApiMethod)
      .GetMethod("HitApi", BindingFlags.Public | BindingFlags.Instance)
      .MakeGenericMethod(genericArg1)
      .Invoke(instanceOfClassContainingHitApiMethod, new object[] { instanceOfApiHelper });
//obj.HitApi(ApiHandlerHelper)
类型(ClassContainingHitApiMethod)
.GetMethod(“HitApi”,BindingFlags.Public | BindingFlags.Instance)
.MakeGenericMethod(genericArg1)
.Invoke(instanceOfClassContainingHitApiMethod,新对象[]{instanceofapiphelper});

那么您是说反射(此解决方案)不适用于T表示不实现任何接口/继承任何类的类的情况?请您解释一下上述签名。我有反射的概念,以及如何在JAVA中实现反射。它看起来没什么不同,但我还是想确保我的思路是正确的。@ArunPandey不,我的意思是你需要强制一个
t
参数来实现或派生一些东西,因为
t
“按原样”作为反射调用的通用参数,将阻止您在编译时将
对象
强制转换为更具体的对象来访问成员,或者您将被迫使用反射实现所有内容,这在当前是不愉快的all@ArunPandey对不起,没关系。我没有注意到您的方法返回
void
。我把那部分从回答中删掉了。检查更新的答案。。所以它对我来说似乎很好,只是有点问题。我重载了HitApi方法,所以在使用反射时,它给了我含糊不清的MatchException。这两种方法接受不同的参数,数量也不同。我还尝试了新对象[]{parameters},但它总是给我一个例外。任何想法,都可能是什么问题。
Type genericArg1 = typeof(T);
// obj.HitApi<T>(ApiHandlerHelper helper)
typeof(ClassContainingHitApiMethod)
      .GetMethod("HitApi", BindingFlags.Public | BindingFlags.Instance)
      .MakeGenericMethod(genericArg1)
      .Invoke(instanceOfClassContainingHitApiMethod, new object[] { instanceOfApiHelper });