[英]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.