C#   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了C#嵌套类/结构可见性大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图弄清楚实现某个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#嵌套类/结构可见性全部内容,希望文章能够帮你解决C#嵌套类/结构可见性所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。