VB.NET函数以字符串形式获取属性名称 [英] VB.NET function get property name as string
问题描述
我正在尝试创建一个函数,当将属性作为参数传递给它时,它返回用于将属性定义为字符串的名称.例如
I'm trying to create a function that when a property is passed to it as a parameter, it returns the name used to define the property as a string. For example,
Shared Function PropertyToStr(Propert As Object)
'Code to get property name and return it as a string goes here
End Function
提供First_Name
是属性的名称,定义如下:
Providing that First_Name
is a the name of a property, defined like:
Property First_Name as String
该功能应类似于:
Dim str as String = PropertyToStr(First_Name) ' Resulting in str = "First_Name"
请注意,我只希望在此函数中返回属性名称"First_Name",而不是例如"MyClass.First_Name".
Note I ONLY want in this function to return the property name "First_Name", and not "MyClass.First_Name" for example.
我发现了其他一些与我的函数相似的代码示例,我需要用c#编写,但是我无法在VB.Net中复制它们对MemberExpression的使用
I have found other examples of similar code to my function I require written in c# yet I have not been able to replicate their use of the MemberExpression in VB.Net
推荐答案
在Visual Studio 2015中,您可以使用NameOf
运算符来完成此操作:
In Visual Studio 2015 you can use the NameOf
operator to accomplish this:
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早期版本的原始答案:
Original answer for older versions of .net:
通过一些代码转换器运行其他答案并清理它会产生以下效果,看来效果很好.
Running those other answers through some code converters and cleaning it up yields the following, which seems to work just fine.
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
这篇关于VB.NET函数以字符串形式获取属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!