c# - 将接口(interface)实现从 VB.NET 转换为 C#

标签 c# .net vb.net interface

这似乎是一个显而易见的答案,但我似乎找不到答案。我在 VB.NET 中有这段代码:

Public Interface ITestInterface
    WriteOnly Property Encryption() As Boolean
End Interface

而且我在 VB.NET 中也有这个类和实现:

Partial Public Class TestClass
    Implements ITestInterface

    Public WriteOnly Property EncryptionVB() As Boolean Implements ITestInterface.Encryption
        Set(ByVal value As Booleam)
             m_Encryption = value
        End Set
    End Property
End Class

我正在尝试将其转换为 C#。我已经很好地转换了 C# 接口(interface),如下所示:

public interface ITestInterface
{
    bool Encryption { set; }
}

问题是,如何将实现转换过来。我有这个:

public partial class TestClass
{
    public bool Encryption 
    {
         set { m_Encryption = value; }
    }
}

问题在于,在 C# 中,您似乎必须将函数命名为与您正在实现的接口(interface)函数相同的名称。如何调用此方法 EncryptionVB 而不是 Encryption,但仍实现 Encryption 属性?

最佳答案

我能想到的最接近的方法是使用显式实现:

public partial class TestClass : ITestInterface
{
    public bool EncryptionVB
    {
         ((ITestInterface)this).Encryption = value;
    }

    bool ITestInterface.Encryption { set; }
}

现在,从表面上看,这似乎“不是一回事”。但它确实是。考虑这样一个事实,在 VB.NET 中,当您命名一个实现接口(interface)成员的成员与接口(interface)定义的内容不同时,这个“新名称”只有在您在编译时知道类型时才会出现。

所以:

Dim x As New TestClass
x.EncryptionVB = True

但如果上面代码中的x 被键入为ITestInterface,则该EncryptionVB 属性将不可见。它只能作为加密访问:

Dim y As ITestInterface = New TestClass
y.Encryption = True

事实上,这与 C# 中的显式接口(interface)实现完全相同。看看等效代码:

TestClass x = new TestClass();
x.EncryptionVB = true;

ITestInterface y = new TestClass();
y.Encryption = true;

关于c# - 将接口(interface)实现从 VB.NET 转换为 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3692507/

相关文章:

.net - 有没有免费的库可以在 .NET 中播放各种声音格式?

c# - 如何重构重载方法

javascript - 如何在 JavaScript 中运行 shell 命令

vb.net - 发送电子邮件后无法删除 PDF 文件

javascript - AngularJS 将数据作为键值对发布到 asp.net 页面

C# CheckedListBox.ItemCheck 事件

c# - 如果在 C# 中的 Using 语句中调用连接关闭事件会发生什么

c# - 如何检测非英文输入?

c# - 当我通过 ReportViewer 生成报告时禁用 Excel 导出选项

c# - 无法在 NetworkService 帐户中启动 Windows 服务