【问题标题】:How to overload the Items accessor of a Collection(Of T)?如何重载 Collection(Of T) 的 Items 访问器?
【发布时间】:2015-12-17 10:40:23
【问题描述】:

下面的代码是用 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")

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

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

【问题讨论】:

  • 看起来你正在滚动你自己的字典类...
  • 当“Name=”这样的条目出现在多个部分时会发生什么?
  • @Plutonix 在真正的源代码中,每个部分都由一个名为 IniSection 的对象表示,该对象包含仅引用该部分的键。感谢您的评论。
  • 我只是好奇。并非没有,但在当今时代,使用序列化而不是 INI,您可以为自己省去很多麻烦和代码。
  • @Plutonix 你的好奇心没问题,我喜欢回答。我对特定的事情使用 Xml 序列化,但 INI 文件最好由终端服务器动态编辑,在我看来,INI 文件是软件的“便携式”设置的最佳选择。

标签: c# .net vb.net generics collections


【解决方案1】:

您要查找的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)

【讨论】:

    【解决方案2】:

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

    Collection(Of T).Item Property (Int32)

    我该怎么做?

    Default Public Overloads ReadOnly Property Item(ByVal keyName As String) As IniKey
        Get
        End Get
    End Property
    

    【讨论】:

    • 感谢您在 Vb.Net 中的额外回答。
    猜你喜欢
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 2010-09-30
    相关资源
    最近更新 更多