0

例子:

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; }
        }



    }
}

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

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

4

2 回答 2

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; }
        }
    }
}
于 2013-07-15T20:33:39.833 回答
2

class ExtremasForX更改to的访问修饰符public并将其构造函数更改为internal而不是public,如下所示:

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);

    }

    public class ExtremasForX
    {
        private BoundingBox box;
        internal 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; }
        }



    }
}
于 2013-07-15T20:34:02.400 回答