我正在尝试创建一个函数,当一个属性作为参数传递给它时,它返回用于将属性定义为字符串的名称.例如,
Shared Function PropertyToStr(Propert As Object) 'Code to get property name and return it as a string goes here End Function
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
编辑:在Visual Studio 2015中,您可以使用NameOf运算符来完成此操作:
原文链接:https://www.f2er.com/vb/255319.htmlProperty 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