如何创建一个可用作外部类中的公共字段的私有嵌套类?

Tho*_*mas 0 c#

例:

public class BoundingBox
{
    public Vector3Double Positon { get; set; }
    public Vector3Double Apothem { get; set; }
    public ExtremasForX X;

    public BoundingBox(Vector3Double position, Vector3Double size)
    {
        Positon = position;
        X = new ExtremasForX(this);

    }

    private class ExtremasForX
    {
        private BoundingBox box;
        public ExtremasForX(BoundingBox box)
        {
            this.box = box;
        }
        public double Max
        {   
            get { return box.Positon.X + box.Apothem.X ; }
        }
        public double Min
        {
            get { return box.Positon.X - box.Apothem.X; }
        }



    }
}
Run Code Online (Sandbox Code Playgroud)

此代码生成可访问性错误:BoundingBox.X的级别高于其类型.

我想要一个没有公共构造函数的内部类,因为我只希望将该类用作外部类的命名空间.我该怎么做?

Cra*_*ney 6

如果你真的不想暴露内部类型,你可以让内部类实现一个接口.然后,在外部类中,您将公开X为接口类型,但在内部使用内部类的类型.

就个人而言,我只是将内部阶级公之于众.用户不能通过实例化类来伤害任何东西,因此暴露构造函数并不是什么大问题.

用于通过接口公开内部类型而不暴露构造函数的代码:

public class BoundingBox
{
    public Vector3Double Positon { get; set; }
    public Vector3Double Apothem { get; set; }
    public IExtremasForX X { get { return _x; } }
    private ExtremasForX _x;

    public BoundingBox(Vector3Double position, Vector3Double size)
    {
        Positon = position;
        _x = new ExtremasForX(this);
    }
    public interface IExtremasForX {
        public double Max { get; }
        public double Min { get; }
    }

    private class ExtremasForX : IExtremasForX
    {
        private BoundingBox box;
        public ExtremasForX(BoundingBox box)
        {
            this.box = box;
        }
        public double Max
        {   
            get { return box.Positon.X + box.Apothem.X ; }
        }
        public double Min
        {
            get { return box.Positon.X - box.Apothem.X; }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)