<分区>
考虑这个问题 String.Split
overload ,它需要一个 StringSplitOptions
枚举作为参数。
枚举本身是公开的并且可供包括 System 命名空间的所有内容访问,这不是很糟糕吗?我的意思是,枚举完全特定于 Split
方法的选项,但它在其范围之外可用。
也许有更好的方法来对此进行建模,例如将枚举放在 String 类本身中,然后使用 String.SplitOptions
访问它?我很少看到这种情况(实际上我现在不记得有任何这样的情况),所以我认为出于某种原因它不是首选。总的来说,我认为缩小事物的范围是最佳实践,因为可以这么说,因为在不正确的范围内使用类/成员可以降低出现问题的可能性。
我在这里使用 Split
作为示例,但是 Enum
也很常见,它也仅由我们代码库中的方法或类使用。我通常像任何其他类一样在单独的 cs 文件中将枚举创建为公共(public)类型,但我很想听听解决此“问题”的其他方法。
更新:
我刚找到 this article用 Folder
类和 Filter
枚举攻击这个确切的问题,但似乎又违背了我认为在这种情况下更正确的做法(将枚举放在类中不知何故)。其中一条来自 ToddM 的评论(我碰巧同意)指出:
...
But, even then, I feel your logic is wrong. Your main complaint against embedding the enum inside of the class is that it will take too long to type. Given how verbose C# tends to be, this is not really a sensible argument. In VS, CTRL+SPACE is your friend.
Logically, I feel placing the enum inside of the class is far more correct. Take your example: what is a MyNameSpace.Filter? Where does it apply? I guess it's a filter for your namespace? It's impossible to tell, especially if your namespace grows to contain dozens of classes.
Now consider MyNameSpace.Folder.Filter -- it is, in my mind, far more intuitive that Filter applies in some way, shape, or form to the Folder class. Indeed, another class can be added to the namespace with its own concept of filter, one of whose members may be 'File'. Just because you've introduced a new class into the namespace doesn't give you the right to pollute that namespace with various 'helper' types. If you are developing as part of a large development team, your style is, well, rude.
...