半私有内部类

发布于 2024-12-28 06:03:39 字数 853 浏览 3 评论 0原文

我正在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乖乖兔^ω^ 2025-01-04 06:03:39

不可能只对外部类公开它们。
问题是为什么需要将它们公开?如果您创建一个库,您可以使用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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文