在 LinqToSql 结果中通过 MethodName(String) 查找值



假设我的 Person 类看起来像这样:

Private Class Person
    Public Property Name As String
    Public Property Age As Integer
End Class

我有一个名为linqToSqlResult的结果,名称= "John"和年龄= 30。现在我想获取此人的名字,如下所示:

Dim name As String = CStr(GetValue(linqResult, "Name"))

我正在寻找这样的代码:

Private Function GetValue(ByRef linqToSqlResult As Object, fieldName As String) As Object
    'Here's the code I'm looking for??
End Function

知道吗?

由于

缺乏信息,我假设传递的值LinqToSqlResultPerson类型查询的输出,如果没有请更清楚地解释contents of LinqToSqlResult

您可以执行以下操作(尽管不是性能最高的代码段):

Imports System.Reflection

Module Module1
    Sub Main()
        Dim i As Object = New Person With {.Name = "TestUser", .Age = 30}
        Console.WriteLine(GetValue(Of Person)(i, "Name").ToString())
        Console.WriteLine(Convert.ToInt32(GetValue(Of Person)(i, "Age").ToString()))
        Console.ReadLine()
    End Sub

    Private Function GetValue(Of T)(ByRef linqToSqlResult As Object, fieldName As String) As Object
        Dim myProp As PropertyInfo = GetType(T).GetProperties().Where(Function(x) x.Name.Equals(fieldName)).FirstOrDefault()
        If (myProp IsNot Nothing) Then
            Return myProp.GetValue(linqToSqlResult, Nothing)
        Else
            Throw New ArgumentException(" Some usefull message")
        End If
    End Function

End Module

Public Class Person
    Public Property Name As String
    Public Property Age As String
End Class

这输出:

//TestUser
//30

最新更新