从堆栈中的类获取泛型参数 [英] Getting generic arguments from a class in the stack

查看:85
本文介绍了从堆栈中的类获取泛型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Repository的泛型类。这个类有一个调用自己的功能,通过使用不同的泛型参数初始化Repository类的新实例。这种递归可以继续 - 所以为了避免StackOverflowException,我需要检查堆栈中是否存在一个从存储库类调用的具有相同泛型参数的方法。
这里是我的代码:

  StackTrace stack = new StackTrace(); 
StackFrame [] frames = stack.GetFrames();

foreach(StackFrame frame in frame)
{
类型callingMethodClassType = frame.GetMethod()。DeclaringType;
if(callingMethodClassType.IsGenericType)
{
//在这个BUG中获取类的泛型参数
类型genericType = callingMethodClassType.GetGenericArguments()[0];
if(genericType.Equals(entityType))
{
wasAlready = true;
休息;



code
$ b

泛型类型总是返回为T而不是正确的类型,例如User或Employee(例如)。我不能比较类型的名称,因为T没有名称。

解决方案

不要以为这是可能的,因为你只能得到GenericType,而不是类的真正GenericArguments。

如果你看看frame.GetMethod()的返回值。注意,只有GenericType,但不是真正的GenericArguments在调试结果中。


I have a generic class called Repository. This class has a function that "calls itself" by initializing a new instance of the Repository class with a different generic argument. This "recursion" can go on - so to avoid StackOverflowException, i need to check if there is in the stack, a method called from the Repository class with the same generic argument. here is my code:

    StackTrace stack = new StackTrace();
    StackFrame[] frames = stack.GetFrames();

    foreach (StackFrame frame in frames)
    {
        Type callingMethodClassType = frame.GetMethod().DeclaringType;
        if (callingMethodClassType.IsGenericType)
        {
            // BUG HERE in getting generic arguments of the class in stack
            Type genericType = callingMethodClassType.GetGenericArguments()[0];
            if (genericType.Equals(entityType))
            {
                wasAlready = true;
                break;
            }
        }
    }

the generic type always returns as T and not the correct type like "User" or "Employee" (for example). I can't compare the names of the types because T does not have a name.

解决方案

Don't think that this is possible, because you only get the GenericType, but not the real GenericArguments of the class.

If you look at the return of frame.GetMethod().DeclaringType you'll notice, that only the GenericType, but not the real GenericArguments are within the debugging result.

这篇关于从堆栈中的类获取泛型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆