vb 中的枚举错误,与 C# 中的枚举有何不同?
我认为 VB 和 C# 中的枚举是相同的或至少非常相似。今天我在 VB 代码中偶然发现了一个错误。以下 VB 代码编译并运行没有问题:
Enum Cars
Subaru
Volvo
End Enum
Enum Vegtables
Carrots
Beets
End Enum
Sub Main()
Foo(Cars.Subaru)
Foo(Vegtables.Carrots)
End Sub
Public Sub Foo(ByVal value As Cars)
End Sub
但 C# 中的等效代码正确显示错误:
enum Cars
{
Subaru,
Volvo
}
enum Vegtables
{
Carrots,
Beets
}
class Program
{
static void Main(string[] args)
{
Foo(Cars.Subaru);
Foo(Vegtables.Carrots);//<-- C# detects a type mismatch here
}
public static void Foo(Cars carsValue)
{}
}
为什么 VB 版本不能捕获类型不匹配? VB 和 C# 中的枚举有不同吗?
I thought that enums in VB and C# where the same or at least very similar. Then today I stumbled across a bug in our VB code. The following VB code compiles and runs with no issues:
Enum Cars
Subaru
Volvo
End Enum
Enum Vegtables
Carrots
Beets
End Enum
Sub Main()
Foo(Cars.Subaru)
Foo(Vegtables.Carrots)
End Sub
Public Sub Foo(ByVal value As Cars)
End Sub
But the equivalent in C# correctly shows an error:
enum Cars
{
Subaru,
Volvo
}
enum Vegtables
{
Carrots,
Beets
}
class Program
{
static void Main(string[] args)
{
Foo(Cars.Subaru);
Foo(Vegtables.Carrots);//<-- C# detects a type mismatch here
}
public static void Foo(Cars carsValue)
{}
}
Why does the VB version not catch the type mismatch? Are enum in VB and C# different?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您已经从 Bala R 得到了答案 - 尝试
Option Strict On
。并不是枚举本身不同(C# 和 VB.NET 中的声明尽可能彼此等效)很可能会产生相同的 CIL“字节码”)。相反,编译器在编译时提供的类型安全/它们允许的隐式类型强制方面有所不同。
如果类型安全对您来说非常重要,那么枚举可能不是最佳选择。即使 C# 也允许您(显式)将一种
enum
类型的值转换为不同的enum
类型。You already got an answer to that from Bala R — try
Option Strict On
.It's not the
enum
s themselves that are different (your declarations in both C# and VB.NET are as equivalent to one another as they can be and will in all probability result in identical CIL "bytecode"). It's rather that the compilers differ in the type safety they provide at compile-time / the implicit type coercion they allow.If type safety is very important to you, then
enum
s probably aren't the best option. Even C# allows you to (explicitly) cast a value of oneenum
type to a differentenum
type.为 VB.NET 编译打开
Option Strict
选项,它将捕获不匹配的情况。Turn
Option Strict
option for VB.NET compilation and it will catch the mismatch.