gpt4 book ai didi

C# 属性在派生类中不可用

转载 作者:太空狗 更新时间:2023-10-29 22:20:58 26 4
gpt4 key购买 nike

我不确定发生了什么。我有以下基类:

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.Keysbase.Keys,但在 MySubRow 中都不起作用。我尝试在 MyRow 中将 Keys 属性标记为 public 但得到“修饰符‘public’对此项无效”,我认为是因为有必要实现一个接口(interface)。

最佳答案

您正在实现 Keys属性(property)明确。如果您想让该成员可公开访问(或 protected ),请更改 IDictionary<string, string>.KeysKeys并在其前面添加适当的可见性修饰符。

public ICollection<string> Keys { ... }

protected ICollection<string> Keys { ... }

您可以引用 base作为 IDictionary<string, string> 的实例还有:

((IDictionary<string, string>)base).Keys

更多信息

(从您的评论来看,您似乎熟悉其中的区别,但其他人可能不熟悉)

C# 接口(interface)实现可以通过两种方式完成:隐式或显式。让我们考虑一下这个接口(interface):

public interface IMyInterface
{
void Foo();
}

接口(interface)只是类必须让调用它的代码可以使用哪些成员的契约。在本例中,我们有一个名为 Foo 的函数。不接受任何参数并且不返回任何内容。隐式接口(interface)实现意味着您必须公开 public与界面上成员的姓名和签名相匹配的成员,如下所示:

public class MyClass : IMyInterface
{
public void Foo() { }
}

这满足了接口(interface),因为它公开了一个 public匹配接口(interface)上每个成员的类上的成员。这是通常所做的。但是,可以显式实现接口(interface)并将接口(interface)函数映射到private。成员:

public class MyClass : IMyInterface
{
void IMyInterface.Foo() { }
}

这会在 MyClass 上创建一个私有(private)函数只有外部调用者引用 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
}

显式实现始终是私有(private)的。如果你想在类之外公开它,你必须创建另一个成员并公开它,然后使用显式实现来调用另一个成员。通常这样做是为了一个类可以实现接口(interface)而不会弄乱其公共(public) API,或者如果两个接口(interface)公开具有相同名称的成员。

关于C# 属性在派生类中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2148385/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com