【问题标题】:Why does not work the use of an extension method in the same extension method?为什么在同一个扩展方法中使用扩展方法不起作用?
【发布时间】:2015-02-05 11:06:51
【问题描述】:

我得到了一个扩展方法,它为我提供了实例中每个属性的值。对于标量值,它工作得很好。但是对于Collections 来说有一个问题。这是我的代码:

<Extension()>
Public Function ToXml(Of T)(ByVal source As T) As XmlDocument
    Dim oXmlDocument As New XmlDocument
    oXmlDocument.AppendChild(oXmlDocument.CreateXmlDeclaration("1.0", "utf-8", Nothing))
    oXmlDocument.AppendChild(oXmlDocument.CreateElement(XmlConvert.EncodeName(source.GetType.ToString)))

    For Each Item As System.Reflection.FieldInfo In source.GetType.GetFields
        Dim oElement As XmlElement = oXmlDocument.CreateElement(XmlConvert.EncodeName(Item.MemberType.ToString))
        oElement.Attributes.Append(oXmlDocument.CreateAttribute("Name")).Value = Item.Name
        oElement.Attributes.Append(oXmlDocument.CreateAttribute("Value")).Value = Item.GetValue(source)

        oXmlDocument.DocumentElement.AppendChild(oElement)
    Next

    For Each Item As System.Reflection.PropertyInfo In source.GetType.GetProperties
        Dim oElement As XmlElement = oXmlDocument.CreateElement(XmlConvert.EncodeName(Item.MemberType.ToString))
        oElement.Attributes.Append(oXmlDocument.CreateAttribute("Name")).Value = Item.Name

        If (Not (TryCast(Item.GetValue(source, Nothing), ICollection) Is Nothing)) Then
            For Each SubItem As Object In CType(Item.GetValue(source, Nothing), ICollection)
                For Each Node As XmlNode In SubItem.ToXml().DocumentElement.SelectNodes("node()")
                    oElement.AppendChild(oElement.OwnerDocument.ImportNode(Node, True))
                Next
            Next
        Else
            oElement.Attributes.Append(oXmlDocument.CreateAttribute("Value")).Value = If(Not (Item.GetValue(source, Nothing) Is Nothing), Item.GetValue(source, Nothing).ToString, "Nothing")
        End If

        oXmlDocument.DocumentElement.AppendChild(oElement)
    Next

    Return oXmlDocument
End Function

线

For Each Node As XmlNode In SubItem.ToXml().DocumentElement.SelectNodes("node()")

抛出错误Public member 'ToXml' on type 'MyClass' not found.

如果我这样做了

Dim instance As new MyClass
instance.ToXml()

这也有效。我的错在哪里?

提前感谢您的任何回复。

【问题讨论】:

    标签: vb.net reflection extension-methods dynamic-programming generic-programming


    【解决方案1】:

    在 VB.NET 中,为了向后兼容,扩展方法不适用于声明为 Object 的变量。

    试试:

    Dim instance As Object = new MyClass()
    instance.ToXml()
    

    它会失败。

    所以你不能在SubItem 上调用ToXml,因为SubItem 的类型是Object。


    但是,您可以像常规方法一样调用ToXml:

    For Each Node As XmlNode In ToXml(SubItem).DocumentElement.SelectNodes("node()")
    

    【讨论】:

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