【发布时间】:2015-11-23 18:24:12
【问题描述】:
考虑以下类:
public class Vehicle { ... }
public class Coverage { ... }
public class VehicleList : IEnumerable<Vehicle> { ... }
public class CoverageList : IEnumerable<Coverage> { ... }
public abstract class Quote
{
protected VehicleList vehicles;
protected CoverageList coverages;
internal Quote() { ... }
public IReadOnlyCollection<Vehicle> Vehicles
{
get { return this.vehicles.AsReadOnly(); }
}
public IReadOnlyCollection<Coverage> Coverages
{
get { return this.coverages.AsReadOnly(); }
}
...
}
public sealed class OhQuote : Quote
{
//needs to access protected fields
...
}
public sealed class InQuote : Quote { ... }
public sealed class MiQuote : Quote { ... }
Quote 完全封装了VehicleList 和CoverageList 的功能,所以我想将这些类标记为internal。问题是它们是protected 类的protected 字段的类型。如果我将这些字段标记为protected internal,那么它们就是protected 或internal。我真正需要的是让他们成为protected 和internal(protected 在程序集中优先)。您可以看到Quote(具有internal 构造函数)及其子类(sealed)都不能在程序集之外扩展。我已经想出了如何使用公共接口实现所需的功能,但想确保没有更简洁的方法。
【问题讨论】:
-
创建一个封装受保护字段的内部属性
-
@Gusman 仍然会将受保护的字段公开给程序集中类的消费者。
-
抱歉,但我不太明白您的要求,受保护的字段将始终对任何消费者可见,无论它在哪里定义,并且内部属性将始终可见到同一个程序集中的所有类,所以程序集中的消费者可以看到“受保护的内部”,那么你想要什么?
-
Okoko,现在我明白了,它应该只有通过在你的程序集中继承类才能看到,对吧?
-
@Gusman 是的,没错。
标签: c# oop inheritance protected