2013-06-26 51 views
0

我需要一个字典,可以这样做:辞典类型值

Dictionary properties = new Dictionary(); 
properties.Add<PhysicalLogic>(new Projectile(velocity)); 

// at a later point 
PhysicalLogic logic = properties.Get<PhysicalLogic>(); 

我发现this制品,它类似于我想要的东西,但并不完全。

Unity3D做它用自己GetComponent<>()方法,所以它应该是可能的: http://docs.unity3d.com/Documentation/ScriptReference/GameObject.GetComponent.html (点击“JavaScript的”下拉列表中看到C#版本)

回答

4

没有内置的类,它这一点。

public class TypedDictionary { 
    private readonly Dictionary<Type, object> dict = new Dictionary<Type, object>(); 

    public void Add<T>(T item) { 
     dict.Add(typeof(T), item); 
    } 

    public T Get<T>() { return (T) dict[typeof(T)]; } 
} 

注意,这将根据他们的编译时类型添加项目,并且您将无法解析:

您可以通过包装一Dictionary<Type, object>和铸造结果Get<T>()自己写一个使用除确切类型以外的任何东西(与基本类型或可变换类型相反)。

如果你想克服这些限制,可以考虑使用完整的IoC系统,比如Autofac,它可以完成所有这些工作。

字典不能帮助那里,因为类型可转换性不是等价关系。
例如,stringint都应计为object,但这两种类型不相等。

+0

这很好。无论如何,我可以得到像这样的东西来处理它呢? properties.Add (someVar); –

1

严格按照你的例子(即一类只能有一个条目)就可以实现这个双向的:

自定义词典

public class TypedDictionary : Dictionary<Type, object> 
{ 
    public void Add<T>(T value) 
    { 
     var type = typeof (T); 

     if (ContainsKey(type)) 
      this[type] = value; 
     else 
      Add(type, value); 
    } 

    public T Get<T>() 
    { 
     // Will throw KeyNotFoundException 
     return (T) this[typeof (T)]; 
    } 

    public bool TryGetValue<T>(out T value) 
    { 
     var type = typeof (T); 
     object intermediateResult; 

     if (TryGetValue(type, out intermediateResult)) 
     { 
      value = (T) intermediateResult; 
      return true; 
     } 

     value = default(T); 
     return false; 
    } 
} 

扩展方法

public static class TypedDictionaryExtension 
{ 
    public static void Add<T>(this Dictionary<Type, object> dictionary, T value) 
    { 
     var type = typeof (T); 

     if (dictionary.ContainsKey(type)) 
      dictionary[type] = value; 
     else 
      dictionary.Add(type, value); 
    } 

    public static T Get<T>(this Dictionary<Type, object> dictionary) 
    { 
     // Will throw KeyNotFoundException 
     return (T) dictionary[typeof (T)]; 
    } 

    public static bool TryGetValue<T>(this Dictionary<Type, object> dictionary, out T value) 
    { 
     var type = typeof (T); 
     object intermediateResult; 

     if (dictionary.TryGetValue(type, out intermediateResult)) 
     { 
      value = (T) intermediateResult; 
      return true; 
     } 

     value = default(T); 
     return false; 
    } 
} 

第一种方法更明确,因为另一种方法只需要特定ic类型的字典。