VB.NET函数将属性名称作为字符串

时间:2015-01-20 01:57:16

标签: .net vb.net function properties parameters

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

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

1 个答案:

答案 0 :(得分:10)

编辑:在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