我正在寻找一种检索变量名称的方法,因此我不必在需要时使用硬编码声明(对于属性名称等):
我几乎不相信这是可能的;也许有人有解决方案。
注意:即使不是变量,属性也会移动。
'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
欢迎用 VB 或 C# 提供答案。
哦,有一个简单的解决方案,使用表达式树这里是一个例子,只需适应你在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"
我第一次看到这个,真是一个启示! ;)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)