以类型为值的字典

Ben*_*ell 1 c# dictionary types

我需要一本可以做到这一点的字典:

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

// at a later point
PhysicalLogic logic = properties.Get<PhysicalLogic>();
Run Code Online (Sandbox Code Playgroud)

我发现这篇文章与我想要的内容相似,但不完全相同。

Unity3D 使用他们的GetComponent<>()方法来完成它,所以它应该是可能的:http : //docs.unity3d.com/Documentation/ScriptReference/GameObject.GetComponent.html (单击“JavaScript”下拉列表以查看 C# 版本)

SLa*_*aks 5

没有内置类可以做到这一点。

您可以通过包装 aDictionary<Type, object>并将结果转换为Get<T>()

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)]; }
}
Run Code Online (Sandbox Code Playgroud)

请注意,这将根据它们的编译时类型添加项目,并且您将无法使用除确切类型(与基本类型或可变可转换类型相反)以外的任何内容进行解析。

如果您想克服这些限制,请考虑使用像 Autofac 这样的完整 IoC 系统,它可以完成所有这些甚至更多。

字典无济于事,因为类型可转换性不是等价关系。
例如,两者stringint都应该算作object,但这两种类型并不相等。