枚举和枚举有什么区别使用带有常量的静态类?
这两项之间的性能影响是什么?我最近在野外看到了静态类,但我不知道如何理解它。
public enum SomeEnum
{
One = 1,
Two,
Three
}
public static class SomeClass
{
public static readonly int One = 1;
public static readonly int Two = 2;
public static readonly int Three = 3;
}
What are the performance implications between these two items? I've seen the static class in the wild recently and I'm not sure what to make of it.
public enum SomeEnum
{
One = 1,
Two,
Three
}
public static class SomeClass
{
public static readonly int One = 1;
public static readonly int Two = 2;
public static readonly int Three = 3;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
区别在于类型安全。假设您有两个这样的枚举。你将如何区分:
vs
所以到处你都有一个想要成为一组特定值之一的表达式,你可以让读者都清楚和 如果您使用枚举,编译器您对哪一组值感兴趣。只有整数...没那么多。
The difference is type safety. Suppose you have two of these enums. How are you going to tell the difference:
vs
So everywhere you have an expression which wants to be one of a particular set of values, you can make it clear to both the reader and the compiler which set of values you're interested in if you use enums. With just ints... not so much.
枚举直接嵌入在 IL 中,而字段(如类中的字段)将需要字段加载指令,这可能会稍微昂贵一些。以下是调用接受枚举与字段的方法的 IL 代码。
Enums are embedded directly in IL whereas fields (like the ones you have in your class) will need a field load instruction which may be slightly more expensive. Here is the IL code for calling a method that accepts an enum versus fields.
好吧,一方面,类型安全,至少是不容易被规避的类型安全。例如,使用枚举值,我可以创建一个函数原型,例如
void Foo( SomeEnum value );
而对于静态类,我必须采用 int 参数。当然,您可以放弃类型安全,但它更容易使用,也更明显,而且您还可以更轻松地执行转换。此外,枚举还提供自动递增值、调试器中的漂亮打印支持、与属性网格等控件的绑定优势。你明白了。
Well, for one, type safety, at least, type safety that is not as easily circumvented. For example, using an enumerated value I can create a function prototype such as
void Foo( SomeEnum value );
Whereas with your static class I would have to take an int parameter. Sure, you can cast away the type safety, but it's easier to use and makes it more obvious, and you can also perform conversions more easily. Also, enum's give auto incremented values, pretty-print support in the debugger, binding benefits with controls like a property grid. You get the idea.