J
J
Jen992019-03-12 22:19:28
C++ / C#
Jen99, 2019-03-12 22:19:28

How to get element by type in Dictionary?

I wrote a class that will store the components. Components will be implemented from different classes. The studio says that you cannot use T by key in GetComponent. What would be the right way to implement it. Maybe there is a method in the Dictionary that allows me to solve my problem?

public class DictComponent
  {
    public Dictionary<Type, Component> Components { get; private set; }

    public DictComponent()
    {
      Components = new Dictionary<Type, Component>();
    }

    public T GetComponent<T>()
    {
      // НЕ РАБОТАЕТ
      return (T)Components[T.GetType()];
    }

    public void Add(Component comp)
    {
      Components[comp.GetType()] = comp;
    }
  }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
freeExec, 2019-03-12
@Jeen99

public Component GetComponent<T>()
{
      // РАБОТАЕТ
      return Components[typeof(T)];
}

J
Jeen99, 2019-03-12
@Jeen99

I noticed that all the same solutions are different.

public T GetComponent<T>()
    {
      return (T)Components[typeof(T)];
    }

My version is better, because the object is returned exactly with the type requested.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question