[英]Using a variable and a set value inside the convert.ToDateTime function
[英]Convert a Variable To a Propery Variable Using Reflection
我正在嘗試轉換
Public Class TestClass
Public FirstName As String
End Class
至
Public Class AnotherClass
Public Property FirstName As String
End Class
我編寫了一個將一個類的成員轉換為另一個類的成員的函數,因此,如果我傳遞某個具有Public Property LastName AS String
類類型,它將把它轉換為(例如) AnotherClass Type
變量,並且我能夠獲得價值,所以我在這里很高興。
Public Shared Function ConvertModelToValidationDataModel(Of T)(ByVal oSourceObject As Object) As T
Dim oSourceObjectType As Type
Dim oSourceObjectProperties() As PropertyInfo
Dim oDestinationObjectProperties() As PropertyInfo
Dim oDestinationObject As Object
Dim oDestinationObjectType As Type
oDestinationObject = Activator.CreateInstance(Of T)()
oDestinationObjectType = GetType(T)
oDestinationObjectProperties = oDestinationObjectType.GetProperties
oSourceObjectType = oSourceObject.GetType()
oSourceObjectProperties = oSourceObjectType.GetProperties()
If Not oSourceObjectProperties Is Nothing Then
If oSourceObjectProperties.Count > 0 Then
For Each oDestinationObjectPropertyInfo As PropertyInfo In oDestinationObjectProperties
For Each oSourceObjectPropertyInfo As PropertyInfo In oSourceObjectProperties
If oDestinationObjectPropertyInfo.Name = oSourceObjectPropertyInfo.Name Then
oDestinationObjectPropertyInfo.SetValue(oDestinationObject, oSourceObjectPropertyInfo.GetValue(oSourceObject, Nothing))
End If
Next
Next
End If
End If
Return oDestinationObject
End Function
問題是我想傳遞TestClass
( 變量FirstName
不是屬性,但我希望將其轉換為屬性變量 )並能夠將其轉換並獲取值,但是由於某種原因,它不傳遞值,顯然它看起來像函數將其轉換為另一個類的非屬性變量-不是我想要的屬性變量 。
**
**
當我傳入具有屬性變量的類類型( Public Property FirstName As String
)時,我獲得了另一種類型的類,則所有值都被傳遞並轉換為屬性變量。
當我傳入具有變量的類類型( Public FirstName As String
)時,我無法獲取該值,並且無法將其轉換為屬性變量。
問題:為什么在傳遞具有非屬性變量的類類型時無法獲得該值並將其轉換為屬性變量?
感謝下面評論部分中的人幫助我直觀地看到了這樣一個事實:我在向對象詢問屬性,而對象只有字段。
這是該功能的更新版本
Public Shared Function ConvertModelToValidationDataModel(Of T)(ByVal oSourceObject As Object) As T
Dim oSourceObjectType As Type
Dim oSourceObjectFields() As FieldInfo
Dim oDestinationObjectProperties() As PropertyInfo
Dim oDestinationObject As Object
Dim oDestinationObjectType As Type
oSourceObjectType = oSourceObject.GetType()
oSourceObjectFields = oSourceObjectType.GetFields()
oDestinationObject = Activator.CreateInstance(Of T)()
oDestinationObjectType = GetType(T)
oDestinationObjectProperties = oDestinationObjectType.GetProperties
If Not oSourceObjectFields Is Nothing Then
If oSourceObjectFields.Count > 0 Then
For Each oSourceObjectFieldInfo As FieldInfo In oSourceObjectFields
For Each oDestinationObjectPropertyInfo As PropertyInfo In oDestinationObjectProperties
If oSourceObjectFieldInfo.Name = oDestinationObjectPropertyInfo.Name Then
oDestinationObjectPropertyInfo.SetValue(oDestinationObject, oSourceObjectFieldInfo.GetValue(oSourceObject))
End If
Next
Next
End If
End If
Return oDestinationObject
End Function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.