微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将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#项目中引用它.否则,转换它是安全的,但您必须更改使用它的任何代码以返回不同的类型.

原文地址:https://www.jb51.cc/vb/255414.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐