2

我正在使用 VB.Net 2010。我想复制由外部(非自我)应用程序输入到我的应用程序的(COM)对象的内容。我不想一一复制字段和属性值(因为可能会在未来的应用程序构建中添加或删除字段/属性)。

对象类型是不可序列化的。

我已经尝试如下反射(在线程复制一个对象到另一个对象上建议的 VB 代码):

Imports System.Reflection

Public Class ObjectHelper

    ' Creates a copy of an object
    Public Shared Function GetCopy(Of SourceType As {Class, New})(ByVal Source As SourceType) As SourceType

        Dim ReturnValue As New SourceType
        Dim sourceProperties() As PropertyInfo = Source.GetType().GetProperties()

        For Each sourceProp As PropertyInfo In sourceProperties
            sourceProp.SetValue(
                ReturnValue, 
                sourceProp.GetValue(Source, Nothing),
                Nothing)
        Next

        Return ReturnValue

    End Function

End Class

这不起作用,因为返回的sourceProperties()数组是空的。

有任何想法吗?

4

1 回答 1

0

首先在实现中有一个bug

Dim sourceProperties() As PropertyInfo = Source.GetType().GetProperties()

应该

Dim sourceProperties() As PropertyInfo = GetType(SourceType).GetProperties()

Source.GetType()返回_COMObject类型,因为那是对象的真实类型,而您确实想检查对象实现的接口类型。

其他解决方案是检查对象是否实现了任何IPersist接口并将其用于真正的 COM 序列化。您可以通过将对象转换为 eg 来做到这一点System.Runtime.InteropServices.ComTypes.IPersistFile。不幸的是,其他 IPersist* 接口未在该命名空间中定义,因此您必须从某个地方导入它们。

于 2013-03-14T15:28:37.760 回答