我试图创建一个可以与数据行接口并自动填充其所有数据的Inherit类。为此,我创建了一个这样的词典:
reyRelation As New Dictionary(Of String, String)
rey.Add("Id", "id_user")
rey.Add("Name", "name")
rey.Add("Surname", "surname")
其中"键"是财产的名称,以及"值"是DataRow对象中列的名称。
所以,我想创建一个名为" load"的函数。例如,像这样:
Try
Dim row As DataRow = Me.getRowById()
For Each key As String In Me.reyRelation.Keys
Me.key = getRowById(reyRelation.Item(key))
Next
Catch ex As Exception
MessageBox.Show(ex.Message, "MODEL Error in Utente: Errore caricamento dati", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
其中:
1 -
Me.getRowById()
是声明为MustOverride
的类中的函数,因此每个类都可以使用正确的dataAdapter。2 -
Me.key
显然是我的问题的焦点:我不能做这样的事情,因为我发现了一个错误,所以问题是:我如何从在属性中设置字符串key
以设置其值?
我希望我能解释清楚! 谢谢!
答案 0 :(得分:0)
我已经找到了@Mark建议的答案(谢谢你,对于我关于C#和vb的愚蠢问题而感到抱歉),所以这就是解决我问题的代码,希望对其他人有帮助! / p>
Public Sub load()
Try
Dim row As DataRow = Me.getRowById()
For Each key As String In Me.reyRelation.Keys
If key <> "Id" Then
Dim type As Type = Me.GetType
Dim propInfo As System.Reflection.PropertyInfo = type.GetProperty(key)
Dim value As Object = row.Item(reyRelation.Item(key))
If value Is DBNull.Value Then
propInfo.SetValue(Me, value.ToString, Nothing)
Else
propInfo.SetValue(Me, value, Nothing)
End If
End If
Next
Catch ex As Exception
MessageBox.Show(ex.Message, "MODEL Error in Utente: Errore caricamento dati", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub