从堆栈中的类获取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(); }
试试这个
上述就是C#学习教程:从堆栈中的类获取generics参数分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
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; }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1018016.html