如何解决实现接口但具有不同的属性名称
我虽然这很容易,但我在 VB.Net 中有这样的代码:
Sub Main
Dim foo As IMyInterface(Of String) = New Cander()
foo.Items.Add("Hello")
Debug.WriteLine(foo.Items.First())
End Sub
Interface IMyInterface(Of Out T)
ReadOnly Property Items As List(Of String)
End Interface
Public Class Cander
Implements IMyInterface(Of String)
Private _anyName As List(Of String)
Public ReadOnly Property AnyName As List(Of String) Implements IMyInterface(Of String).Items
Get
If _anyName Is nothing Then
_anyName = New List(Of String)
End If
Return _anyName
End Get
End Property
End Class
所以我可以在接口 Items
属性和类 AnyName
属性中使用不同的名称。因此,如果我尝试将此代码转换为 C#,它应该是这样的:
public void Main()
{
IMyInterface<string> foo = new Cander();
foo.Items.Add("Hello");
Debug.WriteLine(foo.Items.First());
}
// Define other methods and classes here
interface IMyInterface<out T>
{
List<string> Items { get; }
}
public class Cander : IMyInterface<string>
{
private List<string> _anyName;
public List<string> AnyName //I don't kNow how to translate Implements IMyInterface(Of String).Items
{
get
{
if (_anyName == null)
_anyName = new List<string>();
return _anyName;
}
}
}
我不知道如何翻译 Implements IMyInterface(Of String).Items
代码。是一个基本问题,但我搜索了文档和其他答案,但找不到任何解决方案。也许它可以使用
Explicit Interface Implementation 但我找不到类似的解决方案。
在 C# 中可以吗?
解决方法
是的,这是 C# 和 VB.NET 之间的区别之一,是的,您可以使用显式接口实现:
public class Cander : IMyInterface<string>
{
private List<string> _anyName;
public List<string> AnyName
{
get
{
if (_anyName == null)
_anyName = new List<string>();
return _anyName;
}
}
List<string> IMyInterface<string>.Items => AnyName;
}
请注意,这并不完全等同于 VB.NET 版本:AnyName
成员没有以任何方式实现 IMyInterface<string>.Items
:我们正在做的是定义一个新属性实现 IMyInterface<string>.Items
但它不显示为 Cander
的成员,并且它的 getter 调用 AnyName
。
如果 Items
有一个 getter 和一个 setter,你就必须写得稍微迂回一点:
interface IMyInterface<out T>
{
List<string> Items { get; set; }
}
public class Cander : IMyInterface<string>
{
private List<string> _anyName;
public List<string> AnyName //I don't know how to translate Implements IMyInterface(Of String).Items
{
get
{
if (_anyName == null)
_anyName = new List<string>();
return _anyName;
}
set => _anyName = value;
}
List<string> IMyInterface<string>.Items
{
get => AnyName,set => AnyName = value,}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。