我有一个接口(interface)需要实现方括号运算符。从这个继承的类实现它。然而,它也继承自 Dictionary<>,其中实现了相同的运算符:
public interface IFoo
{
IBar this[String tFooName] { get; }
}
[Serializable]
public class ConcreteFoo: Dictionary<String, Bar>, IFoo
{
// Implement interface by calling the dictionary
public IBar this[String tFooName] { get { return this[tFooName]; } }
// .... more code ....
}
当我尝试使用代码时,编译器引用了已实现的直接接口(interface),并说我无法分配给它:
MyClass[tKeyStr] = new Bar();
错误是正确的。因此,我删除了 IFoo 接口(interface)的实现,并希望通过继承 Dictionary<> 来自动实现它。它没有按照我想要的方式进行。
我收到错误“没有实现接口(interface)成员...”。
如果不将字典设为私有(private)成员,我将如何解决这个问题?有办法吗?
请您参考如下方法:
它真的需要从Dictionary<string, Bar>派生吗? ?根据我的经验,直接从 Dictionary<TKey, TValue> 派生很少是个好主意。 , List<T>等等 - 只有为继承明确设计的集合(例如 Collection<T> )通常适合继承。
你能不能不做你的 ConcreteFoo有一个Dictionary<string, Bar> 字段 代替?您在最后一个问题中提到了这一点,但不清楚为什么您尝试使用继承而不是组合。
如果你真的必须使用继承,你可以使用explicit interface implementation ,像这样:
IBar IFoo.this[String tFooName] { get { return this[tFooName]; } }
...但我建议改用组合。
