【问题标题】:.Net 2 version of Element At.Net 2 版本的 Element At
【发布时间】:2014-07-07 11:25:17
【问题描述】:

我正在尝试重新创建我最初在 .net 4 中编写的一段代码,以便它可以在 .Net 2 中运行

有问题的代码如下,导致问题的行是 For next 块中间的行。具体错误是 ElementAt 不是 system.collections.Generic.List(Of String) 的成员。

Public Function GetListOfAvailableC1Themes() As List(Of String)
    Dim lPath As String = Application.StartupPath & "\Themes"
    Dim lThemeList As New List(Of String)
    If Not Directory.Exists(lPath) Then
        Throw New DirectoryNotFoundException("Could not find the 'Themes' directory.")
    Else
        Dim lst As New List(Of String)
        lst.AddRange(Directory.GetFiles(lPath))
        For i As Integer = 0 To lst.Count - 1
            lThemeList.Add(Path.GetFileNameWithoutExtension(lst.ElementAt(i)))
        Next
        Return lThemeList
    End If

End Function

显然我已经意识到这可能最早是在 .Net3.5 之前才引入的。

那么在 .net 2.0 之前,为了达到同样的结果,人们会做些什么呢?

谢谢

【问题讨论】:

  • 你说得对,Enumerable.ElementAt() 扩展方法是后来添加的,它是在 .NET 3.5 中引入的。只需使用列表的索引器 (lst(i))。

标签: .net vb.net collections


【解决方案1】:

您可以只使用索引器,例如

lst(i)

或者

lst.item(i)

【讨论】:

  • 谢谢艾伦,只是票
【解决方案2】:

ElementAt(index) 在任何实现IEnumerable 接口的类中都有效。所以,它对List(Of T) 有效,但在List(Of T) 中你也可以直接使用index,例如list(index),你会得到这个索引中的对象。在IEnumerable 中不是索引集合,这就是ElementAt 方法存在的原因。

【讨论】:

    猜你喜欢
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    相关资源
    最近更新 更多