C # - Create a dictionary <T, Manager <T>>

I have a generic class named Manager<T>, and I want to create a dictionary that maps the type to an instance of the Manager class of this type. I was thinking of creating a Dictionary class that comes from Dictionary, but overriding all of its methods seems redundant. Ideas? Thank.

+5
source share
4 answers

Assuming that your dictionary should contain managers with mixed type arguments, you can implement the interface IManagerin Manager<T>, make Dictionary<Type,IManager>and add a common shell to return the instances back to Maanger<T>, for example this:

interface IManager {
    // Properties and methods common to all Maanger<T>, regardless of T
}

class Manager<T> : IManager {
}

class Main {
    private readonly IDictionary<Type,IManager> managers =
        new Dictionary<Type,IManager>();

    bool TryGetManager<T>(Type key, out Manager<T> manager) {
        IManager res;
        return managers.TryGetValue(key, out res) ? ((Manager<T>)res) : null;
    }
}
+2
source

, , , , , . , Dictionary<Type,Object> Dictionary<Type,IManager>, IManager - () , Manager<T>. T, . , ,

public class ManagerDictionary{
    private Dictionary<Type, object> _managers = new Dictionary<Type, object>();

    public Manager<T> GetManager<T>()
    {
        if (_managers.ContainsKey(typeof(T)))
        {
            return _managers[typeof(T)] as Manager<T>;
        }
        throw new ArgumentException("No manager of " + typeof(T).Name + " could be found");
    }

    public void AddManager<T>(Manager<T> manager)
    {
        _managers.Add(typeof(T),manager);
    }
}
+2

, T. T, .

class Manager<T> where T: IMyClass

, - , T generic.

- , .

+1

, :

class ManagerDictionary<T> : Dictionary<T, Manager<T>> {

}
0

All Articles