[英]Generic class inherit from Dictionary with Collection
I have this custom Dictionary with Collection definition: 我有这个带有集合定义的自定义词典:
class CollectionDictionary<K, C, V> : Dictionary<K, C> where C : ICollection<V>, new()
and using it like this (eg): 并像这样使用它(例如):
CollectionDictionary<Guid, HashSet<int>, int> sample;
but for me this double int
seems awkward, is there a possibility to bypass this and only write: 但对我来说,这个double
int
似乎很尴尬,是否有可能绕过它而只写:
CollectionDictionary<Guid, HashSet<int>> sample;
so that the compiler knows that V
could only be an int? 这样编译器知道
V
只能是int吗?
EDIT: 编辑:
I need the class to abstract this method 我需要类来抽象此方法
public void Add(K key, V value)
{
if (!this.ContainsKey(key))
{
base.Add(key, new C());
}
this[key].Add(value);
}
You can do this 你可以这样做
class CollectionDictionary<K, C> : Dictionary<K, ICollection<C>>
It removes the constraint you had that makes the ICollection
have an empty constructor. 它消除了使
ICollection
具有空构造函数的约束。
In order to be able to create new collections you could ask for a delegate that does that. 为了能够创建新的集合,您可以要求一个这样做的代表。 But in your case I think your original solution would produce less boilerplate code.
但是对于您而言,我认为您的原始解决方案将产生更少的样板代码。
// ctor
public CollectionDictionary(Func<ICollection<C>> collectionCreator)
// Create
base.Add(key, _collectionCreator());
// Init
new CollectionDictionary<Guid, int>(() => new HashSet<int>());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.