【问题标题】:Error with extension method in VB.NETVB.NET 中的扩展方法错误
【发布时间】:2012-04-09 21:38:38
【问题描述】:

我正在尝试在 VB.NET 中编写扩展方法

Imports System.Runtime.CompilerServices

Module ExtensionMethods

    <Extension()> _
    Public Function FindByText(ByVal collection As ListItemCollection, text As String, comparisonType As StringComparison) As ListItem
        Dim result As ListItem = collection.OfType(Of ListItem)().FirstOrDefault(Function(s) s.Text.Equals(text, comparisonType))
        Return result
    End Function

    <Extension()> _
    Public Function FindByValue(ByVal collection As ListItemCollection, text As String, comparisonType As StringComparison) As ListItem
        Dim result As ListItem = collection.OfType(Of ListItem)().FirstOrDefault(Function(s) s.Value.Equals(text, comparisonType))
        Return result
    End Function

End Module

但是我收到了这个错误。

类“System.Web.UI.WebControls.ListItem”无法编入索引,因为 它没有默认属性

可能出了什么问题?

我是这样调用代码的。

ddlSalesmanager.Items.FindByText(survey, StringComparison.CurrentCultureIgnoreCase)

P.S: 我把this wonderful code from C# 移植到了VB

【问题讨论】:

  • 使用collection.Cast(Of ListItem)() 而不是collection.OfType(Of ListItem)(),因为ListItemCollection 中的所有对象本质上都是ListItem 类型。
  • 除了 taht,错误肯定在其他地方,向我们展示您使用这些扩展的代码。
  • 您的 FindByText 声明的参数与您用来调用它的参数不同?
  • 我认为问题是我希望第一个参数是需要扩展的项目,第二个参数是函数的逻辑流程

标签: asp.net vb.net extension-methods


【解决方案1】:
  1. 您的代码有效,因此必须在其他地方引发异常(survey 是什么?)。
  2. 使用collection.Cast(Of ListItem)() 而不是collection.OfType(Of ListItem)(),因为ListItemCollection 中的所有对象本质上都是ListItem 类型。

经过测试

<asp:DropDownList ID="DdlFoo" runat="server" AutoPostBack="true" OnSelectedIndexChanged="FooSelected" >
    <asp:ListItem Text="Foo1" Value="1"></asp:ListItem>
    <asp:ListItem Text="Foo2" Value="2"></asp:ListItem>
    <asp:ListItem Text="Foo3" Value="3"></asp:ListItem>
</asp:DropDownList>

SelectedIndexChanged 事件处理程序中:

Dim foo2 = DirectCast(sender, DropDownList).Items.FindByText("FOO2", StringComparison.CurrentCultureIgnoreCase)
If Not foo2 Is Nothing Then
    ' your overloaded extension is called successfully
End If

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多