半私有内部类
我正在 C# 中实现联合查找数据结构。这些元素必须扩展 Element 内部类,但我想将该类中的字段保持对外部世界私有。然而,它们需要向直接外部阶级公开。由于“可访问性不一致”,以下代码无法编译:
class DisjointSetForrests<T> where T : DisjointSetForrests<T>.Element {
private class PrivateElement {
public Element p;
public int rank;
}
public class Element : PrivateElement {
}
public void MakeSet(T x) {
x.p = x;
x.rank = 0;
}
public T FindSet(T x) {
if (x != x.p) x.p = FindSet(x);
return (T)x.p;
}
public void Union(T x, T y) {
Link(FindSet(x), FindSet(y));
}
public void Link(T x, T y) {
if (x.rank > y.rank) {
y.p = x;
} else {
x.p = y;
if (x.rank == y.rank) y.rank++;
}
}
}
有没有办法实现我想要的,或者我应该接受 Element 中的字段是公共的?
I'm implementing a union-find data structure in C#. The elements must extend the Element inner-class, but I'd like to to keep the fields in that class private to the outside world. They need to be public to the direct outer-class, however. The folloowing code does not compile due to "inconsistent accessibility":
class DisjointSetForrests<T> where T : DisjointSetForrests<T>.Element {
private class PrivateElement {
public Element p;
public int rank;
}
public class Element : PrivateElement {
}
public void MakeSet(T x) {
x.p = x;
x.rank = 0;
}
public T FindSet(T x) {
if (x != x.p) x.p = FindSet(x);
return (T)x.p;
}
public void Union(T x, T y) {
Link(FindSet(x), FindSet(y));
}
public void Link(T x, T y) {
if (x.rank > y.rank) {
y.p = x;
} else {
x.p = y;
if (x.rank == y.rank) y.rank++;
}
}
}
Is there a way to achieve what I want, or should I accept the fields in Element being public?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不可能只对外部类公开它们。
问题是为什么需要将它们公开?如果您创建一个库,您可以使用
internal
。It's not possible to keep them only public to the outer class.
The question is why do you need to keep them public? If you creating a library you could use
internal
.