c# - 在 C# 中限制访问枚举参数的最佳实践

标签 c# .net enums coding-style

<分区>

考虑这个问题 String.Split overload ,它需要一个 StringSplitOptions枚举作为参数。

枚举本身是公开的并且可供包括 System 命名空间的所有内容访问,这不是很糟糕吗?我的意思是,枚举完全特定于 Split 方法的选项,但它在其范围之外可用。

也许有更好的方法来对此进行建模,例如将枚举放在 String 类本身中,然后使用 String.SplitOptions 访问它?我很少看到这种情况(实际上我现在不记得有任何这样的情况),所以我认为出于某种原因它不是首选。总的来说,我认为缩小事物的范围是最佳实践,因为可以这么说,因为在不正确的范围内使用类/成员可以降低出现问题的可能性。

我在这里使用 Split 作为示例,但是 Enum 也很常见,它也仅由我们代码库中的方法或类使用。我通常像任何其他类一样在单独的 cs 文件中将枚举创建为公共(public)类型,但我很想听听解决此“问题”的其他方法。

更新:

我刚找到 this articleFolder 类和 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.

...

最佳答案

嵌套 enum 是一个有趣的想法,以表明它具有缩小的范围,或赋予它更好的语义。我以前使用过这个想法,以便在后编译器中同时拥有错误代码和警告代码 I developed .这样,我可以使用嵌套在 Error class 中的相同枚举名称 CodeWarning class .

另一方面,通常不鼓励公共(public)嵌套类型。它们可能会使必须使用外部类名称限定它们的客户感到困惑。看相关指南on MSDN .一些相关的:

DO NOT use public nested types as a logical grouping construct; use namespaces for this.

AVOID publicly exposed nested types. The only exception to this is if variables of the nested type need to be declared only in rare scenarios such as subclassing or other advanced customization scenarios.

DO NOT use nested types if the type is likely to be referenced outside of the containing type.

For example, an enum passed to a method defined on a class should not be defined as a nested type in the class.

我相信在开发 StringSplitOptions 枚举以及 BCL 中的大多数其他枚举时遵循了这些指南。

关于c# - 在 C# 中限制访问枚举参数的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19450929/

相关文章:

c++ - 从包装类公开内部类的公共(public)枚举

c# - NPGSQL:使用 LWGEOMCOLLECTION 类型调用的关联操作

c# - 检查json数组是否存在c#

c# - 无论如何要加快这个功能?

c# - 如何同时部署两个 ClickOnce 版本?

.net - Log4Net 文件附加程序不记录

c# - 在 WCF MessageEncoder 中获取 HTTP header

objective-c - 是否可以在与在 Objective-C 中使用它的类头文件相同的文件中定义枚举?

Java - 在自身内部使用枚举值

返回 LINQ 时的 c# 异步