加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-17 00:18:58 所属栏目:大数据 来源:网络整理
导读:我有以下需要移植到C#的VB.net接口. C#不允许接口中的枚举.如何在不更改使用此接口的代码的情况下移植它? Public Interface MyInterface Enum MyEnum Yes = 0 No = 1 Maybe = 2 End Enum ReadOnly Property Number() As MyEnumEnd Interface 简而言之,您不
我有以下需要移植到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#项目中引用它.否则,转换它是安全的,但您必须更改使用它的任何代码以返回不同的类型.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读