我有一个抽象
ParentClass
,其中包含一个私有 PrivateThing
类,我不想将其暴露给派生类,而是向其提供 ThingContainer
.
但是,没有访问修饰符可以使
ThingContainer.Things
对 ParentClass
可见;
protected
/internal
:
PrivateThing
是私有的。ThingContainer.Things
暴露给派生类,这是不可取的。有没有办法在不暴露
ThingContainer.Things
的情况下让ParentClass
对PrivateThing
可见?
public abstract class ParentClass
{
private sealed class PrivateThing { }
protected sealed class ThingContainer
{
private List<PrivateThing> _things = new();
// Should be visible to ParentClass
private IReadOnlyList<PrivateThing> Things => _things;
public void AddThing()
{
_things.Add(new PrivateThing());
}
}
private readonly List<ThingContainer> _thingContainers = new();
protected void Setup(Action<ThingContainer> setupThings)
{
var container = new ThingContainer();
setupThings(container);
_thingContainers.Add(container);
}
public void ProcessThings()
{
foreach (var thing in _thingContainers.SelectMany(static b => b.Things /* Can't access */))
Console.WriteLine(thing.ToString());
}
}
public sealed class DerivedClass : ParentClass
{
public DerivedClass()
{
Setup(static things =>
{
things.AddThing();
});
}
}