父类访问修饰符

问题描述 投票:0回答:0

我有一个抽象

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();
        });
    }
}
c# inner-classes access-modifiers
© www.soinside.com 2019 - 2024. All rights reserved.