2012-03-26 64 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