C#嵌套类/结构可见性
发布时间:2020-12-16 01:45:11 所属栏目:百科 来源:网络整理
导读:我试图弄清楚实现某个API目标的正确语法是什么,但是我正在努力实现可见性. 我希望能够访问Messenger实例的成员,如msgr.Title.ForSuccesses. 但是,我不希望能够从Messenger类外部实例化Messenger.Titles. 我也愿意制作Messenger.Titles一个结构. 我猜我需要某
我试图弄清楚实现某个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(); } } 解决方法
你只需要将标题设为私有并公开界面而不是它.
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语言中symlink()函数和readlink()函数的使用
- c# – 如何检查List中的值是否存在(超出范围之前
- actionscript-3 – 如何在AS3中透明地处理mouseE
- winapi – 如何使用VB Scripting Host确定路径是
- 【Cocos2d-x】开发实战-Cococs2d-x中的菜单
- ruby-on-rails – Ruby on Rails:如何更改Recor
- 关于React的Container&Presentational Compo
- Oracle里count(1)、count(*)和count(主键)哪个更
- Xcode OSX的向后兼容性
- Swift 使用约束 添加UIView动画
热点阅读