获取变量(不硬codeD)的名字? [英] Get variable (not hard-coded) name?
本文介绍了获取变量(不硬codeD)的名字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要寻找一种方式来获取变量名,这样在需要的时候,我没有使用硬codeD声明(属性名称等。):
I am looking for a way to retrieve the variable name, so I don't have to use hard-coded declarations when needed (for property names etc.):
我几乎不敢相信这是可能的;也许有人有一个解决方案。 注:即使不变量,属性也将是一个移动
I hardly believe it's possible; maybe someone has a solution. Note: even not variables, properties would also be a move.
'Pseudo:
Module Module1
Sub Main()
Dim variable = "asdf"
Dim contact As New Contact
Dim v1 = GetVariableName(variable) 'returns variable
Dim v2 = GetVariableName(contact.Name) 'returns Name
End Sub
Class Contact
Public ReadOnly Property Name()
Get
Return Nothing
End Get
End Property
End Class
Public Function GetVariableName(variable As Object) As String
':}
End Function
End Module
答案是welcommed在任何VB或C#。
Answers are welcommed in either VB or C#.
推荐答案
哦,有一个简单的解决方案,使用前pression树下面是一个例子,只是适应您的需求在C#
Oh there is a simple solution, use expression trees here is an example, just adapt to your needs in c#
string GetPropertyName<T>(Expression<Func<T>> property)
{
MemberExpression ex = (MemberExpression)property.Body;
string propertyName = ex.Member.Name;
return propertyName;
}
现在你可以做
String example = null;
String propertyName = GetPropertyName(()=>example.Length);
//propertyName == "Length"
在我第一次看到,这是一个启示! ;)
The first time I've seen that, it was a revelation ! ;)
这篇关于获取变量(不硬codeD)的名字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文