从堆栈中的类获取generics参数

我有一个名为Repository的generics类。 该类有一个函数,通过使用不同的generics参数初始化Repository类的新实例来“调用自身”。 这个“递归”可以继续 – 所以为了避免StackOverflowException,我需要检查堆栈中是否存在一个从Repository类调用的具有相同generics参数的方法。 这是我的代码:

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; } } } 

generics类型始终返回为T而不是正确的类型,如“User”或“Employee”(例如)。 我无法比较类型的名称,因为T没有名称。

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

如果你看一下frame.GetMethod()。DeclaringType的返回,你会注意到,只有GenericType,而不是真正的GenericArguments都在调试结果中。

由于发布的评论建议使用StackFrame有点棘手且容易出错。 此外,我不确定您是否能够获得有关通用类型的封闭类型的信息。

但是您可以按照另一种方法来维护已经处理的List 。 下面是CreateRepository方法的两个版本,我假设它是您可能用于创建项目存储库的方法。

 private static List addedItemList; has the info of all the created types so far. 

版本 – 1

  public static Repository CreateRepository(T item) { if (addedItemList.Contains(item.GetType())) { return new Repository { Item = item }; } addedItemList.Add(item.GetType()); return CreateRepository(item); } 

版本2

  public static Repository CreateRepository() { if (addedItemList.Contains(typeof(T))) { return new Repository { Item = default(T) }; } addedItemList.Add(typeof(T)); return CreateRepository(); } 

试试这个

 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.GetFullName.Equals(entityType.GetFullName)) { wasAlready = true; break; } } } private static String GetFullName(this T type) { return typeof(T).FullName; }