2011-02-04 6 views
0

.net 3.5、VS 2010 ...これはasp.net Webサイト用です。オブジェクトを別のものにコピー

私にはAgencyというクラスがあります。 Agency_Queriesという2番目のクラスがあります。 Agency_Queriesは、Agencyクラスを継承しています。私はAgencyのようなプロパティをAgency_Queriesにコピーする関数を作成しようとしています。私はそれを行う方法を考え出した。しかし、私はそれをより一般的なものにしようとすると、私はクラス名とリストを渡すことができるので、何か間違っている。

したがって(Agency_Queriesの)リストにコピーする必要がある(Agencyの)リストがある場合、次のようなものがあります。

Dim AgencyS As List(Of Agency) = Nothing 
    Dim Oc As New Agency_Controller 
    AgencyS = Oc.GetAgencyData(0) 

    Dim AgencyQueriesS As New List(Of Agency_Queries) 
    Dim _itemProperties() As Reflection.PropertyInfo = AgencyS.Item(0).GetType.GetProperties() 
    For Each item In AgencyS 
     Dim X As NewAgency_Queries 
     _itemProperties = item.GetType().GetProperties() 
     For Each p As Reflection.PropertyInfo In _itemProperties 
      For Each s As Reflection.PropertyInfo In X.GetType().GetProperties() 
       If p.Name = s.Name Then 
        s.SetValue(X, p.GetValue(item, Nothing), Nothing) 
       End If 
      Next 
     Next 
     AgencyQueriesS.Add(X) 
    Next 

問題は、この新しいジェネリックをDim Xで新しいAgency_Queriesとして作成するときです。どのように私は一般的な意味でクラスの新しいインスタンスを作成するつもりです。私はそれを新しいインスタンスにするか、AgencyQueriesSリストに追加するたびにすべてのオブジェクトが同じデータ値を持つようにする必要があります。ここで

Shared Function CopyObject(ByVal inputList As Object, ByVal OutputClass As Object, ByVal outputList As Object) As Object 
     Dim _itemProperties() As Reflection.PropertyInfo = inputList.Item(0).GetType.GetProperties() 
     For Each item In inputList 
      Dim oClean As Object = OutputClass 
      For Each p As Reflection.PropertyInfo In _itemProperties 
       For Each s As Reflection.PropertyInfo In oClean.GetType().GetProperties() 
        If p.Name = s.Name Then 
         s.SetValue(oClean, p.GetValue(item, Nothing), Nothing) 
        End If 
       Next 
      Next 
      outputList.Add(oClean) 
     Next 
     Return outputList 
    End Function 

おかげ シャノン

答えて

3

を動作していない...ジェネリック版である私は、この、その少しを取り、これを思い付いた:

して申し訳ありません
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 
+0

遅い応答..私はコードを試して、各ループのための行に、エラーメッセージを取得する - プロパティセットメソッドが見つかりません。 – jvcoach23

+1

"プロパティセットメソッドが見つかりません。"あなたはReadOnlyプロパティを持っている可能性があります。 – Dan

+0

各ループの中で、現在のプロパティが読み取り専用であるかどうかを確認し、SetValue行を実行するかどうかを確認する必要があります。したがって、基本的には次のものが必要です。 sourceProp.CanWriteの場合sourceProp.SetValue(ReturnValue、sourceProp.GetValue(Source、Nothing)、Nothing) – Marko

関連する問題