gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:34:13 25 4
gpt4 key购买 nike

这似乎是一个显而易见的答案,但我似乎找不到答案。我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com