简体   繁体   中英

C# type of generic class that inherits from abstract class

I'm struggling to find an easy way of getting the type based on a generic class that inherits from an abstract class.

I have this hierarchy:

public abstract class BaseItemData {}

public abstract class WearableItemData : BaseItemData {}

----
public class EquipmentItemData : WearableItemData {}

public class WeaponItemData : WearableItemData {}

----

public class Item<T> : ScriptableObject {}

public class EquipmentItem : Item<EquipmentItemData> { }

public class WeaponItem : Item<WeaponItemData> { }

With this, I would like to get all Scriptable Objects Assets at editor time. im bulding custom editor with Odin Inspector and would like to add all assets of type Item to the tree but I can't do because of the generic type that need to be passed to Item

   protected override OdinMenuTree BuildMenuTree() {
        OdinMenuTree tree = new OdinMenuTree();
    
    // THIS WORKS
        tree.AddAllAssetsAtPath("TEMPLATES/Weapons", "Assets/Scriptable/Templates", typeof(WeaponItem));
        tree.AddAllAssetsAtPath("TEMPLATES/Equipment", "Assets/Scriptable/Templates", typeof(EquipmentItem));

   // BUT I WOULD LIKE TO HAVE SOMETHING MORE LIKE THIS

        tree.AddAllAssetsAtPath("TEMPLATES", "Assets/Scriptable/Templates", typeof(Item)); // or typeof(Item<WearableItemData>)
    
        return tree;
      }

These works

typeof(Item<WeaponItemData>)
typeof(Item<EquipmentItemData>)
typeof(WeaponItem)
typeof(EquipmentItem)

But these don't as I thought they would ( apparently abstract class don't work???)

typeof(Item<BaseItemData>)
typeof(Item<WearableItemData>)

How can I make so typeof(Item<WearableItemData>) would work? (May it be Odin specific?? (editor time?))

Make a class for all of the non-generic stuff (or just leave empty):

public class ItemBase : ScriptableObject 
{
    /* nothing, or non-generic stuff here */
}

Then, inherit from it for the generic item you have now:

public class Item<T> : ItemBase 
{
    /*...*/
}

Then, you can use tree.AddAllAssetsAtPath("TEMPLATES", "Assets/Scriptable/Templates", typeof(ItemBase));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM