[英]C# property not available in derived class
我不确定发生了什么。 我有以下基类:
public class MyRow : IStringIndexable, System.Collections.IEnumerable,
ICollection<KeyValuePair<string, string>>,
IEnumerable<KeyValuePair<string, string>>,
IDictionary<string, string>
{
ICollection<string> IDictionary<string, string>.Keys { }
}
然后我有这个派生类:
public class MySubRow : MyRow, IXmlSerializable, ICloneable,
IComparable, IEquatable<MySubRow>
{
public bool Equals(MySubRow other)
{
// "MyRow does not contain a definition for 'Keys'"
foreach (string key in base.Keys) { }
}
}
为什么我会收到这个错误? “'MyNamespace.MyRow'不包含'Keys'的定义”。 这两个类都在MyNamespace
命名空间中。 我试过访问this.Keys
和base.Keys
并且都不能在MySubRow
。 我尝试在MyRow
中将Keys
属性标记为public
,但得到“修饰符'public'对此项无效”,我认为因为有必要实现一个接口。
您正在显式实现Keys
属性。 如果要使该成员可公开访问(或protected
),请将IDictionary<string, string>.Keys
更改为Keys
并在其前面添加适当的可见性修饰符。
public ICollection<string> Keys { ... }
要么
protected ICollection<string> Keys { ... }
您可以将base
引用为IDictionary<string, string>
的实例:
((IDictionary<string, string>)base).Keys
更多信息
(根据你的评论,你似乎熟悉这种区别,但其他人可能不是)
C#接口实现可以通过两种方式完成:隐式或显式。 让我们考虑一下这个界面:
public interface IMyInterface
{
void Foo();
}
接口只是一个类,它必须为调用它的代码提供哪些成员。 在这种情况下,我们有一个名为Foo
函数,它不带任何参数并且不返回任何内容。 隐式接口实现意味着您必须公开与接口上成员的名称和签名匹配的public
成员,如下所示:
public class MyClass : IMyInterface
{
public void Foo() { }
}
这满足了接口,因为它在类上公开了与接口上的每个成员匹配的public
成员。 这就是通常所做的事情。 但是,可以显式实现接口并将接口函数映射到private
成员:
public class MyClass : IMyInterface
{
void IMyInterface.Foo() { }
}
这会在MyClass
上创建一个私有函数,只有当外部调用者引用IMyInterface
的实例时才能访问它。 例如:
void Bar()
{
MyClass class1 = new MyClass();
IMyInterface class2 = new MyClass();
class1.Foo(); // works only in the first implementation style
class2.Foo(); // works for both
}
显式实现始终是私有的。 如果要在类之外公开它,则必须创建另一个成员并公开它,然后使用显式实现来调用其他成员。 通常这样做是为了使类可以实现接口而不会混乱其公共API,或者如果两个接口公开具有相同名称的成员。
既然你实施的IDictionary <TKEY的,TValue>中接口明确,你首先要投this
来IDictionary<string,string>
:
public bool Equals(MySubRow other)
{
foreach (string key in ((IDictionary<string,string>)this).Keys) { }
}
我相信Jared和Adam都是正确的:该属性是在基类上实现的,它导致它不公开。 您应该能够将其更改为隐式实现并使其满意:
public class MyRow : IStringIndexable, System.Collections.IEnumerable,
ICollection<KeyValuePair<string, string>>,
IEnumerable<KeyValuePair<string, string>>,
IDictionary<string, string>
{
ICollection<string> Keys { }
}
protected
将允许继承类来查看它,但没有其他类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.