【问题标题】:How to convert VB.net interface with enum to C#如何将带有枚举的 VB.net 接口转换为 C#
【发布时间】:2010-09-15 18:24:29
【问题描述】:

我有以下需要移植到 C# 的 VB.net 接口。 C# 不允许在接口中进行枚举。如何在不更改使用此接口的代码的情况下移植它?

Public Interface MyInterface

    Enum MyEnum
        Yes = 0
        No = 1
        Maybe = 2
    End Enum

    ReadOnly Property Number() As MyEnum

End Interface

【问题讨论】:

    标签: c# vb.net interface enums


    【解决方案1】:
    public enum MyEnum
    {
        Yes = 0,
        No = 1,
        Maybe = 2
    }
    
    public interface IMyInterface
    {
        MyEnum Number { get; }
    }
    

    【讨论】:

    • 这会破坏使用接口的代码。如果可能的话,我想避免这种情况。
    【解决方案2】:

    简而言之,您不能在不破坏代码的情况下更改该接口,因为 C# 不能在接口中嵌套类型。当您实现 VB.NET 版本的接口时,您指定 Number 将返回 MyInterface.MyEnum 类型:

    class TestClass3 : TestInterfaces.MyInterface
    {
    
        TestInterfaces.MyInterface.MyEnum TestInterfaces.MyInterface.Number
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }
    
    }
    

    但是,由于 C# 不能在接口内嵌套类型,如果您将枚举数从接口中断开,您将返回不同的数据类型:在本例中为 MyEnum。

    class TestClass2 : IMyInterface
    {
    
        MyEnum IMyInterface.Number
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }
    
    }
    

    考虑使用完全限定的类型名称。在 VB.NET 接口中,您的返回类型为

    MyProject.MyInterface.MyEnum

    在 C# 界面中,您有:

    MyProject.MyEnum.

    不幸的是,必须更改实现 VB.NET 接口的代码以支持 MyInterface.Number 返回的类型已更改的事实。

    IL 支持在接口内嵌套类型,所以 C# 不支持的原因是个谜:

    .class public interface abstract auto ansi MyInterface
    

    { .property 实例值类型 TestInterfaces.MyInterface/MyEnum Number { .get 实例值类型 TestInterfaces.MyInterface/MyEnum TestInterfaces.MyInterface::get_Number() }

    .class auto ansi sealed nested public MyEnum
        extends [mscorlib]System.Enum
    

    { .field public static literal valuetype TestInterfaces.MyInterface/MyEnum Maybe = int32(2)

        .field public static literal valuetype TestInterfaces.MyInterface/MyEnum No = int32(1)
    
        .field public specialname rtspecialname int32 value__
    
        .field public static literal valuetype TestInterfaces.MyInterface/MyEnum Yes = int32(0)
    
    }
    

    }

    如果您在使用此接口的其他程序集中有大量代码,最好将其保存在单独的 VB.NET 程序集中,并从您的 C# 项目中引用它。否则,转换它是安全的,但您必须更改任何使用它的代码以返回不同的类型。

    【讨论】:

      猜你喜欢
      • 2019-06-09
      • 1970-01-01
      • 2020-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多