C# 和 VB.NET 中枚举的区别
我们有遗留的字符代码,我们希望将其作为数字存储在新系统中。为了提高开发人员进行迁移的代码的可读性和一般理解,我想像这样进行枚举...
Public Enum Status As Short
Open = AscW("O")
Closed = AscW("C")
Pending = AscW("P")
EnRoute = AscW("E")
End Enum
通过此设置,代码将是可读的(想象一下 If Record.Status = Status.Open
),但这些值将以较小的数字存储在数据库中,因此效率很高。然而...我是一个 VB.NET 人员,但每个人都想用 C# 编写代码,所以我需要 C# 中的这种结构。
经过谷歌搜索后,我发现 AscW
的一般 .NET 等效项是 Convert.ToInt32("C")
。当我尝试在枚举中使用该语句时,出现编译器错误“需要常量表达式”。
我怎样才能在 C# 中做到这一点?有更好的办法吗?
We have legacy character codes that we want to store as numbers in a new system. To increase readibility and general understanding in the code for devs making the migration, I want to do Enums like this...
Public Enum Status As Short
Open = AscW("O")
Closed = AscW("C")
Pending = AscW("P")
EnRoute = AscW("E")
End Enum
With this setup, the code will be readable (imagine If Record.Status = Status.Open
), and yet the values will be stored in the database as small numbers so it will be efficient. However... I am a VB.NET guy, but everybody wants to code in C#, so I need this sort of structure in C#.
After Googling, I discovered the the general .NET equivalent of AscW
is Convert.ToInt32("C")
. When I try to use that statement in an enum, I get the compiler error "Constant Expression Required".
How can I do this in C#? Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
方法调用不是常量表达式。试试这个:
AscW
在 VB 中工作的原因是它是 VB 编译器在编译时理解和计算的内部事物,并被编译器视为常量表达式。即使在 VB 中,Convert.ToInt32
也不起作用。引用 Visual Basic 规范:
A method call is not a constant expression. Try this:
The reason
AscW
works in VB is that it's an internal thing that VB compiler understands and evaluates at compile time and is considered a constant expression by the compiler. Even in VB,Convert.ToInt32
will not work.To quote the Visual Basic specification:
试试这个:
Try this: