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

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

问题描述

凯瑟琳多拉德最近的博客文章,她presents一个有趣的理由使用嵌套类的.NET。不过,她也提到的FxCop不喜欢嵌套类。我假设的人写的FxCop规则是不傻,所以必须有推理背后的位置,但我一直没能找到它。

In Kathleen Dollard's recent 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 static 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.

如果该树节点类是外在的,你要么必须让所有的字段公开或作出了一堆 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天全站免登陆