在 LinqToSql 结果中按 MethodName(String) 查找值?
Find value by MethodName(String) in a LinqToSql result?
假设我的人 class 看起来像这样:
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
有什么想法吗?
由于缺乏信息,我假设作为 LinqToSqlResult
传递的值是 Person
类型查询的输出,如果不是,请更清楚地解释 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
假设我的人 class 看起来像这样:
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
有什么想法吗?
由于缺乏信息,我假设作为 LinqToSqlResult
传递的值是 Person
类型查询的输出,如果不是,请更清楚地解释 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