简体   繁体   English

C#引用的对象集

[英]C# Set of Objects Referenced by Class

What I want is a unique collection, or set, of objects referenced by their class. 我想要的是一个由他们的类引用的对象的唯一集合或集合。 This set can only contain one object of a given class. 该集合只能包含给定类的一个对象。 Here is an example of some possible functionality: 以下是一些可能的功能示例:

class A;
class B;
class C;

A a = new A();
B b = new B();
C c = new C();

UnknownCollection<object> objects;
objects.Add(A, a);    // Add(key, value)
objects.Add(B, b);
objects.Add(C, c);
var something = objects[A]; // return a reference to 'a' using class A as a key

If something along these lines doesn't already exist, might there be a way to create one with reasonable performance? 如果这些行中的某些内容尚不存在,是否可以创建一个具有合理性能的方法?

It sounds like you really want a Dictionary<Type, object> which you populate with: 听起来你真的想要一个填充的Dictionary<Type, object>

objects.Add(typeof(A), a);
objects.Add(typeof(B), a);
objects.Add(typeof(C), a);
...

A a = (A) objects[typeof(A)];

If the dictionary always maps a type to an instance of that type, you can encapsulate that so you can keep the API clean. 如果字典始终将类型映射到该类型的实例,则可以封装该类型,以便保持API清洁。 You always know the cast will work, because the only code which can add to the dictionary ensures that the type is always correct. 您总是知道强制转换是可行的,因为唯一可以添加到字典的代码可确保该类型始终正确。

EDIT: Aha - it turns out I blogged about this back in 2008 . 编辑:啊哈 - 事实证明我在2008年发表了关于此的博客

You are looking for a Dictionary<TKey, TValue> , specifically with type as a key: 您正在寻找一个Dictionary<TKey, TValue> ,特别是类型为键:

Dictionary<Type, object> map = new Dictionary<Type, object>()
{
    { typeof(A), a }
    { typeof(B), b }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM