【问题标题】:Reflection on property - How to use a string to access and set a class property对属性的反思 - 如何使用字符串来访问和设置类属性
【发布时间】:2015-03-07 22:40:28
【问题描述】:

我正在尝试创建一个继承类,该类可以与数据行交互并自动填充其所有数据。为此,我创建了一个这样的字典:

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 访问设置它的值?

我希望我的解释很清楚! 谢谢!

【问题讨论】:

  • C#和vb有相同的sintax吗?抱歉,我不懂 c# 语言..
  • 语法相同,不,但库(例如反射)是相同的,不幸的是,许多可用的 .NET 信息都在 C# 中,因此至少知道如何从 C# 转换为VB.NET。在许多情况下,您只需要删除分号。例如从this answer 你可以做Me.GetType().GetProperty(key).SetValue(Me, getRowById(reyRelation.Item(key)), Nothing)。性能可能是一个问题,因此您可能需要缓存 PropertyInfo 实例或寻找可以为您执行此操作的库(该答案中还提到了一个选项)。
  • 非常感谢!你的解释真的很清楚很有帮助!

标签: vb.net reflection properties


【解决方案1】:

我在@Mark 的建议下找到了答案(感谢您并为我关于 C# 和 vb 的愚蠢问题感到抱歉),所以这就是解决我问题的代码,我希望它对其他人有帮助!

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 2021-07-02
    • 2023-01-25
    相关资源
    最近更新 更多