如何将VB.net接口与枚举转换为C#

我有以下需要移植到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版本的接口时,您指定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 instance valuetype TestInterfaces.MyInterface / MyEnum Number
{
.get instance valuetype 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#项目中引用它.否则,转换它是安全的,但您必须更改使用它的任何代码以返回不同的类型.

相关文章

Format[$] ( expr [ , fmt ] ) format 返回变体型 format$ 强...
VB6或者ASP 格式化时间为 MM/dd/yyyy 格式,竟然没有好的办...
在项目中添加如下代码:新建窗口来显示异常信息。 Namespace...
转了这一篇文章,原来一直想用C#做k3的插件开发,vb没有C#用...
Sub 分列() ‘以空格为分隔符,连续空格只算1个。对所选...
  窗体代码 1 Private Sub Text1_OLEDragDrop(Data As Dat...