dimanche 22 octobre 2017

Getting a class's type after passing it as an ancestor class

I have some classes, for example

  • IntentoryItem, a base class for all items in inventory,
  • Weapon, all the weapons, derived from InventoryItem,
  • Shotgun, Rifle, Handgun etc and many more, all are Weapons.

I have this method:

private void SomeMethod(InventoryItem g)
{
    var myClasses = g.GetType().FindAllDerivedTypes<InventoryItem>();
    //do something with myClass
}

The problem is with FindAllDerivedTypes<InventoryItem>(). If I implement it the way like so:

public static List<Type> FindAllDerivedTypes<T>(this Type type)
{
    return FindAllDerivedTypes<T>(type, Assembly.GetAssembly(typeof(T)));
}

public static List<Type> FindAllDerivedTypes<T>(this Type type, Assembly assembly)
{
    var derivedType = typeof(T);
    return assembly
        .GetTypes()
        .Where(t =>
            t != derivedType &&
            derivedType.IsAssignableFrom(t)
            ).ToList();
}

(as found on another SO thread) I get all the classes that are derived from my InventoryItem, which is fine, but I need only those relevant to my case, so if a Shotgun was passed as an InventoryItem, I want to get a Shotgun, if I pass another one, I want to get it as another one. Question is, what am I doing wrong?

EDIT

The goal:

doesn't matter what InventoryItem I pass, I need to get the passed instance's type, and only that one type. say I call it like so:

Shotgun s = GetShotgunFromSomewhere();

SomeMethod(s);  //here `Shotgun` is an `InventoryItem`, and was passed like that.

However, inside that method I need the Shotgun class, and not an InventoryItem, and I can't cast it by hand like this:

var myVar = (Shotgun)g;

because I have a lot of inventory items and I would have to do all by hand.

g.GetType();

wasn't working out. Should it return a Shotgun or an InventoryItem? Because when using it, I expected a shotgun but got the inventory item.





Aucun commentaire:

Enregistrer un commentaire