我有一小段代碼,它檢查一個類是否存在或不存在。查找泛型反射
起初我加載所有可用的類型:
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這是絕對錯誤的。 –