gpt4 book ai didi

c# - 为什么派生类不能从基类访问 protected getter?

转载 作者:行者123 更新时间:2023-12-02 04:43:39 25 4
gpt4 key购买 nike

我有这样一个类:

public class Base
{
public Base(string name)
{
this.Name = name;
}

public string Name { get; set; }
public string PrettyName
{
get { return Prettify(Name); }
}
}

我从中得出:

public class Derived : Base
{
public Derived(Base b) : base(b.Name) { }
}

不应访问 Name 属性;逻辑名称只能由 PrettyName 访问。所以我想我会像这样制作属性:

    public string Name { protected get; set; }

但是我得到了这个:

Cannot access protected member 'Name' via a qualifier of type 'Base'; the qualifier must be of type 'Derived' (or derived from it)  

这是为什么呢? getter 应该暴露给基类及其所有子类。我这里有什么问题吗?

最佳答案

The getter should be exposed to the base class and all its child classes.

不,不完全是。这不是自动实现属性的问题 - 这是 protected 含义的问题。

访问子类中的 protected 成员必须通过该子类(或进一步的子类)的实例。您不能将 Base.Name 用于 Derived 中的任意 Base

来自 C# 规范的第 3.5.3 节:

When a protected instance member is accessed outside the program text of the class in which it is declared, and when a protected internal instance member is accessed outside the program text of the program in which it is declared, the access must take place within a class declaration that derives from the class in which it is declared. Furthermore, the access is required to take place through an instance of that derived class type or a class type constructed from it. This restriction prevents one derived class from accessing protected members of other derived classes, even when the members are inherited from the same base class.

一个简单的解决方案是在 Base 中重载构造函数:

protected Base(Base b) : this(b.Name)
{
}

然后在 Derived 中:

public Derived(Base b) : base(b) { }

此时,您也可以将 Name setter 设为私有(private) - 或者更好的是,将其设为完全只读:

private readonly string name;
public string Name { get { return name; } }

关于c# - 为什么派生类不能从基类访问 protected getter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20267501/

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