I am using reflection to scan for all the class types that derive (are assignable) from a particular base class. That part works fine. But when I try to filter the resulting list by the IsAbstract property to get a list of only the non-abstract classes, the LINQ query that does the filtering fails to work correctly. Instead, I had to resort to a foreach loop and do it "manually." I tried this query first:
if (!bAcceptAbstract)
retListFiltered = (from typeClass in retList where typeClass.GetType().IsAbstract == false select typeClass).ToList();
But that didn't filter out the class types marked as abstract.
I then tried:
retListFiltered = (from typeClass in retList where !typeClass.GetType().IsAbstract select typeClass).ToList();
But again, no filtering. Why doesn't the LINQ query seem to respect the value of the IsAbstract propery?
Below is the code I ended up having to use:
public static List<System.Type> GetAllDerivedTypes<T>(Assembly primaryAssembly, bool bAcceptAbstract = true) where T : class
{
if (primaryAssembly == null)
throw new ArgumentNullException("The primary assembly is unassigned.");
List<System.Type> retList =
primaryAssembly.GetTypes().Where(type =>
typeof(T).IsAssignableFrom(type))
.ToList();
List<System.Type> retListFiltered = new List<System.Type>();
foreach (System.Type typeClass in retList)
{
if (bAcceptAbstract || !typeClass.IsAbstract)
{
Debug.WriteLine(String.Format("INCLUDED {0} class, abstract value: {1}.", typeClass.Name, typeClass.IsAbstract.ToString()));
retListFiltered.Add(typeClass);
}
else
Debug.WriteLine(String.Format("IGNORED abstract class: {0}.", typeClass.Name));
}
return retListFiltered;
}
Aucun commentaire:
Enregistrer un commentaire