foreach (var item in Assembly.GetExecutingAssembly().GetTypes()
.Where(x => x.BaseType == typeof(Item)))
{
comboBox1.Items.Add(item);
}
comboBox1.DisplayMember = "Name";
Can this be modified so that the list will include all classes that are derived from 'Item' even if they are two or more times removed? (ie: x.BaseType.BaseType == typeof(Item) etc.)
Also, could it be done to filter out all abstract classes?
A simple approach to this is to use IsAssignableFrom
.
foreach (var item in Assembly.GetExecutingAssembly().GetTypes()
.Where(x => typeof(Item).IsAssignableFrom(x) && !x.IsAbstract))
{
//Handle each item
}
Assuming my "Handle each item were a Console.WriteLine(item)
, and I had this class structure:
class ItemBase {}
class Item : ItemBase {}
class SuperItem : Item {}
abstract class SuperSuperItem : SuperItem{}
class UltimateItem : SuperSuperItem {}
The output would be:
Item
SuperItem
UltimateItem
Note that in this case IsAssignableFrom
returns true for itself, which you can easily omit by adding && x != typeof(Item)
to the Where
clause.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments