示例:
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的级别高于其类型。
我想要一个没有公共构造函数的内部类,因为我只希望将该类用作外部类的命名空间。我该怎么办?
答案 0 :(得分: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; }
}
}
}
答案 1 :(得分:2)
将class ExtremasForX
的访问修饰符更改为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; }
}
}
}