0

destroyComponentPacket.Component is an IComponent (an interface). I want to determine the specific class under it automatically, without having to do it manually using switch(). What are the options for doing so?

switch (destroyComponentPacket.Component)
                        {
                            case Tile t:
                                destroyComponentEntity.Detach<Tile>();
                                break;
                            case CollisionActor ca:
                                destroyComponentEntity.Detach<CollisionActor >();
                                break;
                            case Grass g:
                                destroyComponentEntity.Detach<Grass>();
                                break;
                            case Tree t:
                                destroyComponentEntity.Detach<Tree>();
                                break;
                            case Wall w:
                                destroyComponentEntity.Detach<Wall>();
                                break;
                            default:
                                break;
                        }
dclipca
  • 1,739
  • 1
  • 16
  • 51
  • 2
    Does this answer your question? [Finding the Concrete Type behind an Interface instance](https://stackoverflow.com/questions/1159906/finding-the-concrete-type-behind-an-interface-instance) – gunr2171 Mar 20 '22 at 01:46
  • Why you can not call `destroyComponentEntity.Detach()` – Chetan Mar 20 '22 at 06:34
  • @Chetan it's because the detach method accepts only exact, specific classes as opposed to interfaces. – dclipca Mar 20 '22 at 11:32
  • @gunr2171, the Detach method accepts classes only `public void Detach() where T : class { var mapper = _componentManager.GetMapper(); mapper.Delete(Id); }` is it possible to the type to a class? – dclipca Mar 20 '22 at 11:36
  • Even if a full [mcve] isn't possible, can you give more details about your classes? What is `destroyComponentPacket`? Is there a non-generic method `Detach(Type type)` as well as the generic `Detach()`? Or a `Detach(IComponent component)` method that takes an `IComponent` directly? – dbc Mar 20 '22 at 13:47
  • IF there is no `Detach(Type)` method, you can use `MakeGenericMethod()` to call `Detach()` via reflection, using `destroyComponentPacket.Component.GetType()` as the generic type. See [How do I use reflection to call a generic method?](https://stackoverflow.com/q/232535/3744182), which may be a duplicate. – dbc Mar 20 '22 at 13:49
  • Trying to make a Detach method that accepts type. – dclipca Mar 20 '22 at 14:58

0 Answers0