私有嵌套静态类-好的还是不好的做法? [英] Private nested static class - Good or bad practice?

查看:78
本文介绍了私有嵌套静态类-好的还是不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将私有静态类嵌套在非静态类中是否会被视为不良做法?

Would it be considered a bad practice to nest a private static class inside of a non-static class?

public class Outer
{
    private static class Inner
    {


    }
}

这里的想法是所有外部"实例将共享对静态状态的访问.做到这一点的另一种方法可能是让Inner类是非静态的,并使用它的静态实例:

The idea here is that all instances of 'Outer' would share access to the static state. Another way to do it might be to just let the Inner class be non-static and use a static instance of it:

public class Outer
{
    private static innerInstance = new Inner(); 

    private class Inner
    {


    }
}

类似的效果.这种方法的优点/缺点或其他考虑因素是什么?

Similar effect. What are the pros / cons or other considerations with this approach?

我必须承认我几乎从不从未使用过嵌套类,无论是否是静态的,但我对这个特定概念很感兴趣.

I must admit that I almost never use nested classes, whether static or not, but I am interested in this particular concept..

推荐答案

这两种方法都是完全有效的.

Both approaches are entirely valid.

我希望开发人员会更频繁地使用私有嵌套类.结合使用c#的 partial 关键字,它使编写非常复杂的类变得更加可维护.想象一下,需要构建一个具有小型应用程序复杂性的类-当您实际上可以构建整个私有应用程序时,要容易得多,而该类完全属于您的复杂外部类内部!

I wish developers would use private nested classes more often. In conjunction with c#'s partial keyword, it makes writing very complex classes much more maintainable. Imagine needing to build a class that has the complexity of a small application - much easier when you actually can build an entire private application, with classes that are totally internal to your complex outer class!

我看到的一个非常常见的情况是可枚举-这些可能非常复杂,特别是当您开始构建可以链接的自定义迭代器时,例如 LINQ .隐藏各个类内部的复杂性就是封装的定义.

One very common case I've seen is enumerables - these can be quite complex, especially when you start building custom iterators that can be chained, like LINQ. Hiding the complexity inside the individual classes is the very definition of encapsulation.

这篇关于私有嵌套静态类-好的还是不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆