.net 3.5, VS 2010 ... 이것은 asp.net 웹 사이트를위한 것입니다.한 객체를 다른 객체로 복사
나는 Agency라는 클래스가 있습니다. Agency_Queries라는 두 번째 클래스가 있습니다. Agency_Queries는 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리스트에 추가 될 때마다 모든 객체가 동일한 데이터 값을 가질 필요가있다. 대한
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
미안 : 여기
하지 내가 이것 저것 조금했다이 함께했다 – jvcoach23"속성 집합 메서드를 찾을 수 없습니다." 아마도 당신은 ReadOnly 속성을 가지고 있음을 의미합니다. – Dan
각 루프마다 현재 속성이 읽기 전용인지 확인한 다음 SetValue 행을 실행해야하는지 확인해야합니다. 그래서 기본적으로 필요합니다 : if sourceProp.CanWrite 다음 sourceProp.SetValue (ReturnValue, sourceProp.GetValue (Source, Nothing), Nothing) – Marko