bool InContext(Class array, Item item)
{
for(int i = 0;i<array.length;i++)
{
if(item is array*)*
{
return true;
}
}
return false;
}
Is there anyway to store a bunch of classes so that I can tell if one of my items is inheriting from it?
I want this function for checking if an item is within context (for context sensitive menus) to be fairly dynamic; so writing it in manually isn’t really an option.
Assuming that you have items hierarchy like this
class Item
{
}
class ItemChild1 : Item
{
};
class ItemChild2 : Item
{
};
class ItemChild3 : Item
{
}
you can use the next code to check if an item is of one of the expected types:
// Array of expected classes
Type[] classes = { typeof(ItemChild1), typeof(ItemChild2), typeof(ItemChild3) };
...
// Check the type matching
bool InContext(Type[] array, Item item)
{
if ( item == null )
return false;
for (int i = 0; i < array.Length; i++)
{
if (item.GetType() == array*)*
{
return true;
}
}
return false;
}
// LINQ version
public static bool InContextLINQ(Type[] array, Item item)
{
return ( item != null ) && array.Any(t => item.GetType() == t);
}
Types array elements should not be necessarily inherited from the hypothetical Item parent class - just use some common type to pass the item object to the function (System.Object should be enough).