获取给定类型的集合的引用

Stu*_*urm 7 c#

我有几个词典:

Dictionary<int, Type1> Type1Dictionary { get; set; }
Dictionary<int, Type2> Type2Dictionary { get; set; }
Dictionary<int, Type3> Type3Dictionary { get; set; }
Dictionary<int, Type4> Type4Dictionary { get; set; }
Run Code Online (Sandbox Code Playgroud)

哪里Typei (i = 1..4)派生自相同的基类(BaseType).我想要一个方法,返回给定类型的字典的引用.稍后,我将在该字典上执行一些操作,如添加或删除:

Type1 example = new Type1(); 
var dic = GetDictionary(example);
dic.Add(example.ID, example);
Run Code Online (Sandbox Code Playgroud)

注意:我不想将我的词典设置为 Dictionary<int, BaseType>

我可以写这样的东西,但不会返回对字典的引用:

Dictionary<int, BaseType> GetDictionary(BaseType myObject)
{
    var dic = new Dictionary<int, BaseType>();
    if(myObject is Type1)
    {
    //ideally I would return my Type1Dictionary here but I can't due type incompatibility
       foreach(var x in Type1Dictionary)
       {
            dic.Add(x.Key, x.Value);
       }
       return dic;
    }
    if(myObject is Type2) { /*...*/ }
    if(myObject is Type3) { /*...*/ }
    if(myObject is Type4) { /*...*/ }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

我真正想要的是避免以下结构:

AddObject(BaseType x)
{
    Type1 x1 = x as Type1;
    if(x1 != null) { Type1Dictionary.Add(x1.ID, x1); }

    Type2 x2 = x as Type2;
    if(x2 != null) { Type2Dictionary.Add(x2.ID, x2); }

    Type3 x3 = x as Type3;
    if(x3 != null) { Type3Dictionary.Add(x3.ID, x3); }

    Type4 x4 = x as Type4;
    if(x4 != null) { Type4Dictionary.Add(x4.ID, x4); }
}

RemoveObject(BaseType x)
{
    Type1 x1 = x as Type1;
    if(x1 != null) { Type1Dictionary.Remove(x1.ID); }

    Type2 x2 = x as Type2;
    if(x2 != null) { Type2Dictionary.Remove(x2.ID); }

    Type3 x3 = x as Type3;
    if(x3 != null) { Type3Dictionary.Remove(x3.ID); }

    Type4 x4 = x as Type4;
    if(x4 != null) { Type4Dictionary.Remove(x4.ID); }
}
Run Code Online (Sandbox Code Playgroud)

但反而:

AddObject(BaseType x)
{
    var dic = GetDictionary(x);
    dic.Add(x.ID, x);
}

RemoveObject(BaseType x)
{
    var dic = GetDictionary(x);
    dic.Remove(x.ID);
}
Run Code Online (Sandbox Code Playgroud)

Ond*_*dar 5

这可以根据安全性等方面进行抛光.但是你应该能够得到基本的想法:

public interface IEntity
{
  int ID { get; }
}

public class Superset<T> where T : IEntity
{
  public Dictionary<Type, Dictionary<int, T>> m_Map = 
    new Dictionary<Type, Dictionary<int, T>>();

  private Dictionary<int, T> GetDictionary(Type t)
  {
    Dictionary<int, T> result = null;
    if (!m_Map.TryGetValue(t, out result))
    {
      result = new Dictionary<int, T>();
      m_Map.Add(t, result);
    }
    return result;
  }

  public void Add<K>(K item) where K : T
  {
    GetDictionary(typeof(K)).Add(item.ID, item);
  }

  public bool Remove<K>(K item) where K : T
  {
    return GetDictionary(typeof(K)).Remove(item.ID);
  }
}
Run Code Online (Sandbox Code Playgroud)