C# 嵌套类/结构可见性

标签 c# class syntax struct nested

我试图弄清楚实现特定 API 目标的正确语法是什么,但我在可见性方面苦苦挣扎。

我希望能够访问 Messenger 实例的成员,例如 msgr.Title.ForSuccesses

但是,我不希望能够从我的 Messenger 类之外实例化 Messenger.Titles

我也愿意将 Messenger.Titles 变成一个结构体。

我猜我需要某种工厂模式或其他东西,但我真的不知道该怎么做。

见下文:

class Program {
    static void Main(string[] args) {
        var m = new Messenger { Title = { ForErrors = "An unexpected error occurred ..." } }; // this should be allowed
        var t = new Messenger.Titles(); // this should NOT be allowed
    }
}

public class Messenger {
    // I've tried making this private/protected/internal...
    public class Titles {
        public string ForSuccesses { get; set; }
        public string ForNotifications { get; set; }
        public string ForWarnings { get; set; }
        public string ForErrors { get; set; }

        // I've tried making this private/protected/internal as well...
        public Titles() {}
    }

    public Titles Title { get; private set; }
    public Messenger() {
        Title = new Titles();
    }
}

最佳答案

您只需要将 Titles 设为私有(private)并公开一个接口(interface)而不是它。


class Program {
    static void Main(string[] args) {
        var m = new Messenger { Title = { ForErrors = "An unexpected error occurred ..." } }; // this is allowed
        var t = new Messenger.Titles(); // this is NOT allowed
    }
}

public class Messenger {
    public interface ITitles {
        string ForSuccesses { get; set; }
        string ForNotifications { get; set; }
        string ForWarnings { get; set; }
        string ForErrors { get; set; }
    }

    private class Titles : ITitles {
        public string ForSuccesses { get; set; }
        public string ForNotifications { get; set; }
        public string ForWarnings { get; set; }
        public string ForErrors { get; set; }
    }

    public ITitles Title { get; private set; }
    public Messenger() {
        Title = new Titles();
    }
}

关于C# 嵌套类/结构可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6539225/

相关文章:

c# - 当用户尝试打开相同版本的新实例时,如何返回到已打开的应用程序?

c# - 很难用字典回答自学作业

C++ : "undefined reference to WeightCalc::getHeavier(int)"

c++ - 我什么时候需要默认构造函数?

javascript - 从 iTextSharp 生成 Base64

c# - 通过 oidc-client 登录 IdentityServer4 时出现 InvalidOperationException

ruby - 与另一个类的 Ruby 类实例对话

c# - 为什么我们指定一个委托(delegate)和一个事件,为什么不在 C# 中使用一个事件?

c++ - C++中的继承。为什么错了?

javascript - === 是否存在于 jquery 中