2013-03-13 116 views
2

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

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

我已经试过反思如下(VB代码,建议上线copy one object to another):

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()数组为空。

任何想法?

+0

逐个拷贝值实际上可能不是一个坏主意。这样,你记录了你对每一个属性的想法,并且确信'dest.Prop1 = src.Prop1'确实是复制属性的正确方法(与例如'dest.Prop1 = MakeDeepProp1Copy( src.Prop1)'。 – Heinzi 2013-03-13 16:31:54

+1

你的COM对象是否支持任何'IPersist'接口(http://msdn.microsoft.com/en-us/library/ms688695%28VS.85%29.aspx)?你可以使用如果是的话。 – 2013-03-13 17:54:48

+1

我不知道VB.NET,但不'Source.GetType()'返回'__COMObject'?如果使用VB.NET等效的'typeof '(根据Google,它应该是'GetType(SourceType)')? – 2013-03-13 17:57:06

回答

0

首先出现的是在实现中的错误

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

应该

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

Source.GetType()回报_COMObject类型,那才是真正的类型的对象,而你真的要检查你的接口类型是由对象实现的。

其他解决方案是检查对象是否实现了IPersist interfaces中的任何一个,并将其用于真正的COM序列化。您可以通过将对象投射到例如System.Runtime.InteropServices.ComTypes.IPersistFile。不幸的是,其他IPersist *接口没有在该名称空间中定义,因此您必须从某处导入它们。