Skip to main content
 首页 » 编程设计

c#之如何重载 Collection(Of T) 的 Items 访问器

2024年02月05日18java哥

下面的代码是用 Vb.Net 写的,但我要求一个 Vb.Net 或 C# 示例,无论在答案中。


我有这样一个类型:

Public NotInheritable Class IniKeyCollection : Inherits Collection(Of IniKey) 
 
    Public Sub New() 
    End Sub 
 
    Public Shadows Sub Add(ByVal key As IniKey) 
    End Sub 
 
    Public Shadows Sub Add(ByVal name As String, ByVal value As String) 
    End Sub 
 
    Public Overloads Function Contains(ByVal keyName As String) As Boolean 
    End Function 
 
    Public Overloads Function IndexOf(ByVal keyName As String) As Integer 
    End Function 
 
End Class 

IniKey 是一个具有两个属性的类型:

Public NotInheritable Class IniKey 
 
    Public Property Name As String 
    Public Property Value As String 
 
    Private Sub New() 
    End Sub 
 
    Public Sub New(ByVal name As String) 
        Me.Name = name 
        Me.Value = String.Empty 
    End Sub 
 
    Public Sub New(ByVal name As String, ByVal value As String) 
        Me.Name = name 
        Me.Value = value 
    End Sub 
 
End Class 

我想做的是向 IniKeyCollection 添加一个重载,以通过键名访问 IniKey 元素。

我的意思是,不是默认使用索引:

Dim col As New IniKeyCollection 
Dim item As IniKey = col(index:=0) 

使用字符串:

Dim col As New IniKeyCollection 
Dim item As IniKey = col(keyName:="name") 

...然后在内部(尝试)返回与该键名匹配的元素。

我需要为此操作的基本成员是什么?我该怎么做?

请您参考如下方法:

您要查找的 C# 语言语法项称为索引器。

class IniKeyCollection : Collection<IniKey> 
{ 
 
    private IniKey[] arr = new IniKey[100]; 
 
    public IniKey this[string name] 
    { 
        get 
        { 
            return arr.Where(x => x.Name == name).DefaultIfEmpty(null).Single(); 
        } 
        set 
        { 
            //Not implemented 
        } 
    } 
} 

您可以在以下网址了解更多信息:MSDN - C# Programming Guide (Indexers)