我认为 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# 中的枚举有什么不同吗?
最佳答案
Why does the VB version not catch the type mismatch?
您已经从 Bala R 那里得到了答案——试试 Option Strict On
。
Are enum in VB and C# different?
不是 enum
本身不同(您在 C# 和 VB.NET 中的声明尽可能等同,并且很可能会导致相同的 CIL“字节码” ”)。而是编译器在编译时提供的类型安全性/它们允许的隐式类型强制转换方面存在差异。
如果类型安全对您来说非常重要,那么 enum
可能不是最佳选择。甚至 C# 也允许您(明确地)将一个 enum
类型的值转换为不同的 enum
类型。
关于c# - vb 中的枚举错误,它与 c# 中的枚举有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6930712/