我有一小段代码,它检查一个类是否存在或不存在。查找泛型反射
起初我加载所有可用的类型:
List<Type> types = new List<Type>();
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
{
try
{
types.AddRange(asm.GetTypes());
}
catch (ReflectionTypeLoadException e)
{
types.AddRange(e.Types.Where(t => t != null));
}
}
比我Concat的命名空间和类名(其中应检查):
string fullName = ns.Trim() + "." + classToProof.Trim();
而且在和我请检查是否类存在:
int found = types.Where(innerItem => innerItem.FullName == fullName).ToList().Count;
但我有问题,如果我检查泛型类,例如System.Collections.Generic.Dictionary
,found
总是(应该是1)。
有没有人有一个想法,为什么会发生这种情况?
解决方案:
List<string> types = new List<string>();
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
{
try
{
types.AddRange(asm.GetTypes().Select(item => (!item.FullName.Contains("`") ? item.FullName : item.FullName.Substring(0, item.FullName.IndexOf("`")))));
}
catch (ReflectionTypeLoadException e)
{
types.AddRange(e.Types.Where(t => t != null).Select(item => (!item.FullName.Contains("`") ? item.FullName : item.FullName.Substring(0, item.FullName.IndexOf("`")))));
}
}
我删除了所有`从全名,并填写字符串的准备清单。
谢谢
@MurrayFoxcroft这是绝对错误的。 –