2012-03-26 68 views
0

扩展方法,我试图写在VB.NET错误与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

+0

使用'collection.Cast(中列表项)()',而不是'collection.OfType(中列表项)()',因为['ListItemCollection'](http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.listitemcollection.aspx)中的所有对象的类型都是'ListItem',性质。 – 2012-03-26 11:32:11

+0

除了taht之外,错误必须在其他位置,向我们展示您使用这些扩展名的代码。 – 2012-03-26 11:47:24

+0

您对FindByText的声明有不同于您用来调用它的参数吗? – APrough 2012-03-26 11:58:30

回答

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