vb 中的枚举错误,与 C# 中的枚举有何不同?

发布于 2024-11-27 21:22:43 字数 694 浏览 2 评论 0原文

我认为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

那片花海 2024-12-04 21:22:43

为什么 VB 版本无法捕获类型不匹配的情况?

您已经从 Bala R 得到了答案 - 尝试 Option Strict On

VB 和 C# 中的枚举有不同吗?

并不是枚举本身不同(C# 和 VB.NET 中的声明尽可能彼此等效)很可能会产生相同的 CIL“字节码”)。相反,编译器在编译时提供的类型安全/它们允许的隐式类型强制方面有所不同。

如果类型安全对您来说非常重要,那么枚举可能不是最佳选择。即使 C# 也允许您(显式)将一种 enum 类型的值转换为不同的 enum 类型。

Why does the VB version not catch the type mismatch?

You already got an answer to that from Bala R — try Option Strict On.

Are enum in VB and C# different?

It's not the enums 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 enums probably aren't the best option. Even C# allows you to (explicitly) cast a value of one enum type to a different enum type.

悍妇囚夫 2024-12-04 21:22:43

为 VB.NET 编译打开 Option Strict 选项,它将捕获不匹配的情况。

Turn Option Strict option for VB.NET compilation and it will catch the mismatch.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文