什么是枚举和放大器之间的差异;使用静态类与常量? [英] What's the difference between enums & using static classes with constants?

查看:203
本文介绍了什么是枚举和放大器之间的差异;使用静态类与常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是这两个项目之间的性能有何影响?我见过在野外静态类最近,我不知道该用它来做什么。

 公开枚举SomeEnum 
{
一= 1,
两组,

}

公共静态类SomeClass的
{
公共静态只读诠释一个= 1;
公共静态只读INT两= 2;
公共静态只读INT三= 3;
}


解决方案

的区别是类型安全。假设你有两个这样的枚举。你将如何分辨出来:

 无效的someMethod(INT X,int y)对

//编译,但你想要什么都不会做。
的someMethod(SomeOtherClass.Xyz,SomeClass.One);



VS

 无效的someMethod(SomeEnum X,SomeOtherEnum Y)

//编译时错误
的someMethod(SomeOtherEnum.Xyz,SomeEnum.One)

所以的处处的你有希望成为一组特定值中的一个表达式,你可以把它明确既读者的的哪个设置你感兴趣,如果您使用枚举值的编译器。只需INTS ......与其说


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;
}

解决方案

The difference is type safety. Suppose you have two of these enums. How are you going to tell the difference:

void SomeMethod(int x, int y)

// Compiles, but won't do what you want.
SomeMethod(SomeOtherClass.Xyz, SomeClass.One);

vs

void SomeMethod(SomeEnum x, SomeOtherEnum y)

// Compile-time error
SomeMethod(SomeOtherEnum.Xyz, SomeEnum.One)

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.

这篇关于什么是枚举和放大器之间的差异;使用静态类与常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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