代码之家  ›  专栏  ›  技术社区  ›  Aaron M

在LINQ查询中使用泛型?

  •  1
  • Aaron M  · 技术社区  · 16 年前

    我正在尝试编写一个基于对象列表和对象属性生成Xelement的通用函数。

    目前我把这段代码复制粘贴在几个地方

     InputElementsArray = New XElement(New XElement("ArrayInputs", _
                       New XElement("InputName", "TestFailedRefDesList"), _
                       New XElement("DataType", "StringArray"), _
                       New XElement("ValueList", From d In _PassFailItem.FailureDetails Select New XElement("InputValue", d.RefDes))))
        InputElements.Add(InputElementsArray)
    

    上面的代码对我来说很好,但是我更愿意创建一个函数来完成给定对象和属性的相同任务

    Private Shared Function CreateBaseArrayInputs(Of T)(ByVal ListOfItems As List(Of T)) As XElement
        Dim InputElementsArray As XElement = _
             New XElement("ArrayInputs", _
                      New XElement("InputName", "TestFailureCodeList"), _
                      New XElement("DataType", "StringArray"), _
                      New XElement("ValueList", From d In ListOfItems Select New XElement("InputValue", d)))
        Return InputElementsArray
    End Function
    

    我不确定如何一般地设置要使用的D属性。有什么想法吗?

    3 回复  |  直到 16 年前
        1
  •  3
  •   dahlbyk    16 年前

    除了使用XML文本外,我还将向函数传递值选择器,如下所示:

    Private Shared Function CreateBaseArrayInputs(Of T, TValue)( _
            ByVal ListOfItems As List(Of T), _
            ByVal selector As Func(Of T, TValue)) As XElement
    
        Return <ArrayInputs>
                   <InputName>TestFailureCodeList</InputName>
                   <DataType>StringArray</DataType>
                   <ValueList>
                       <%= From d In ListOfItems _
                           Select <InputValue><%= selector(d) %></InputValue> %>
                   </ValueList>
               </ArrayInputs>
    End Function
    

    您可以这样称呼它:

     Dim TestArray As XElement = CreateBaseArrayInputs(_PassFailItem.FailureDetails, Function(d) d.FailureCodes)
    
        2
  •  0
  •   Jan Aagaard    16 年前

    我认为您不能使用泛型指定属性。I C你这只猫用 where keyword ,但在vb.net中似乎不可用。

    该限制允许您指定T元素必须实现接口,因此您将知道该接口的属性是可用的。

        3
  •  0
  •   Aaron M    16 年前

    我找到了解决这个问题的办法。它没有我想要的那么优雅,但它仍然有效

    这是电话号码

     Dim TestArray As XElement = CreateBaseArrayInputs((From d In _PassFailItem.FailureDetails Select New XElement("InputValue", d.FailureCodes)))
    

    这是被调用的函数

    Private Shared Function CreateBaseArrayInputs(ByVal ListOfItems As IEnumerable(Of XElement)) As XElement
        Dim InputElementsArray As XElement = _
             New XElement("ArrayInputs", _
                      New XElement("InputName", "TestFailureCodeList"), _
                      New XElement("DataType", "StringArray"), _
                      New XElement("ValueList", ListOfItems))
        Return InputElementsArray
    End Function
    
    推荐文章