为什么/什么时候应该在 .net 中使用嵌套类?或者你不应该? [英] Why/when should you use nested classes in .net? Or shouldn't you?

查看:30
本文介绍了为什么/什么时候应该在 .net 中使用嵌套类?或者你不应该?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Kathleen Dollard 2008 年的博文,她提出了在 .net 中使用嵌套类的一个有趣的理由.但是,她还提到 FxCop 不喜欢嵌套类.我假设编写 FxCop 规则的人不傻,所以这个职位背后一定有推理,但我一直没能找到.

In Kathleen Dollard's 2008 blog post, she presents an interesting reason to use nested classes in .net. However, she also mentions that FxCop doesn't like nested classes. I'm assuming that the people writing FxCop rules aren't stupid, so there must be reasoning behind that position, but I haven't been able to find it.

推荐答案

当您嵌套的类仅对封闭类有用时,请使用嵌套类.例如,嵌套类允许您编写类似(简化)的内容:

Use a nested class when the class you are nesting is only useful to the enclosing class. For instance, nested classes allow you to write something like (simplified):

public class SortedMap {
    private class TreeNode {
        TreeNode left;
        TreeNode right;
    }
}

您可以在一个地方对您的类进行完整的定义,您不必跳过任何 PIMPL 圈来定义您的类的工作方式,并且外部世界不需要看到您的任何实现.

You can make a complete definition of your class in one place, you don't have to jump through any PIMPL hoops to define how your class works, and the outside world doesn't need to see anything of your implementation.

如果 TreeNode 类是外部的,则您必须将所有字段设为 public 或创建一堆 get/set 方法来使用它.外部世界将有另一个类污染他们的智能.

If the TreeNode class was external, you would either have to make all the fields public or make a bunch of get/set methods to use it. The outside world would have another class polluting their intellisense.

这篇关于为什么/什么时候应该在 .net 中使用嵌套类?或者你不应该?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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