C#中如何初始化保持protected级别的抽象类字段
报错原因
protected 修饰的成员仅允许在两类位置访问:
- 声明该成员的类(本例中是
Pet类)的内部代码 - 继承自该类的派生类(本例中是
Ant类)的内部代码
你在Program类的Main方法中直接访问ant.description,Program既不是Pet本身也不是Pet的派生类,不具备访问权限,因此会触发编译报错。
可行实现(保持
description字段protected级别不变) 你可以通过派生类Ant对外暴露公开的初始化/赋值入口,在Ant类的内部代码中操作继承来的protected字段,有两种常用写法:
- 方式1:通过构造函数传参初始化
给Ant类添加公开构造函数,接收描述参数,在构造函数内给基类的description字段赋值,实例化时直接传入初始值即可:class Program { static void Main() { Ant ant = new Ant("small"); } } abstract class Pet { protected string description; } class Ant: Pet { protected int group; // 公开构造函数,派生类内部可合法访问基类protected成员 public Ant(string desc) { description = desc; } } - 方式2:通过公开方法/属性赋值
如果需要在对象实例化之后再修改description值,可以在Ant类中添加公开的赋值方法或封装属性,对外提供受控的操作入口:
调用时直接走公开方法即可,不会触发权限错误:class Ant: Pet { protected int group; // 公开赋值方法 public void SetDescription(string desc) { description = desc; } }static void Main() { Ant ant = new Ant(); ant.SetDescription("small"); }
注意:不要为了赋值直接把
description的访问修饰符改成public,会破坏原本的封装设计。
内容的提问来源于stack exchange,提问作者Jr. dective
相关产品推荐
相关产品推荐

