gpt4 book ai didi

.net - VB.NET函数以字符串形式获取属性名称

转载 作者:行者123 更新时间:2023-12-04 10:50:03 25 4
gpt4 key购买 nike

我正在尝试创建一个函数,当将属性作为参数传递给它时,它返回用于将属性定义为字符串的名称。例如,

Shared Function PropertyToStr(Propert As Object)
'Code to get property name and return it as a string goes here
End Function

提供 First_Name是属性的名称,定义如下:
Property First_Name as String

该功能应类似于:
Dim str as String = PropertyToStr(First_Name) ' Resulting in str = "First_Name"

注意我只希望在此函数中返回属性名称“First_Name”,而不是例如“MyClass.First_Name”。

我发现了与我用C#编写的函数相似的代码的其他示例,但我无法在VB.Net中复制其对MemberExpression的使用。

Getting sub property names strongly typed

Get name of property as a string

Retrieving Property name from lambda expression

最佳答案

编辑:在Visual Studio 2015中,您可以使用NameOf运算符来完成此操作:

Property First_Name As String

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MessageBox.Show(NameOf(First_Name))
End Sub

早期版本的.net的原始答案:

通过一些代码转换器来运行其他答案并清理它会产生以下效果,看来效果很好。
Private Shared Function GetMemberInfo(method As Expression) As MemberExpression
Dim lambda As LambdaExpression = TryCast(method, LambdaExpression)
If lambda Is Nothing Then
Throw New ArgumentNullException("method")
End If

Dim memberExpr As MemberExpression = Nothing

If lambda.Body.NodeType = ExpressionType.Convert Then
memberExpr = TryCast(DirectCast(lambda.Body, UnaryExpression).Operand, MemberExpression)
ElseIf lambda.Body.NodeType = ExpressionType.MemberAccess Then
memberExpr = TryCast(lambda.Body, MemberExpression)
End If

If memberExpr Is Nothing Then
Throw New ArgumentException("method")
End If

Return memberExpr
End Function

Public Shared Function GetPropertyName(Of T)(prop As Expression(Of Func(Of T))) As String
Dim expression = GetMemberInfo(prop)
Return expression.Member.Name
End Function

Property First_Name As String
Property LastName As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MessageBox.Show(GetPropertyName(Function() First_Name))
MessageBox.Show(GetPropertyName(Function() LastName))
End Sub

关于.net - VB.NET函数以字符串形式获取属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28036577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com