获取变量(非硬编码)名称?

Shi*_*mmy 3 .net reflection variables declaration

我正在寻找一种方法来检索变量名称,因此我不需要在需要时使用硬编码声明(对于属性名称等):

我几乎不相信这是可能的; 也许有人有解决方案.注意:即使不是变量,属性也会是一个举动.

'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
Run Code Online (Sandbox Code Playgroud)

答案在VB或C#中都很受欢迎.

Fac*_*Vir 5

@Abraham Pinzur; 在链接到的文章中进一步链接后,会提供以下代码段:

static void Main(string[] args)
{
Console.WriteLine("Name is '{0}'", GetName(new {args}));
Console.ReadLine();
}

static string GetName<T>(T item) where T : class
{
var properties = typeof(T).GetProperties();
return properties[0].Name;
}
Run Code Online (Sandbox Code Playgroud)

哪个产生"名字是'args'".Rinat的方法利用C#编译器生成的属性名称在表达式中生成匿名类型new{args}.完整的文章在这里:http://abdullin.com/journal/2008/12/13/how-to-find-out-variable-or-parameter-name-in-c.html

- 编辑 -

进一步阅读Rinat的文章后,也可以通过生成表达式树并浏览树或其包含的IL来完成.基本上,阅读链接的文章!


Nic*_*ier 5

哦有一个简单的解决方案,这里使用表达式树就是一个例子,只需适应你在c#中的需求

string GetPropertyName<T>(Expression<Func<T>> property)
{
    MemberExpression ex = (MemberExpression)property.Body;
    string propertyName = ex.Member.Name;
    return propertyName;
}
Run Code Online (Sandbox Code Playgroud)

现在你可以做到

String example = null;
String propertyName = GetPropertyName(()=>example.Length);
//propertyName == "Length"
Run Code Online (Sandbox Code Playgroud)

我第一次看到它,这是一个启示!;)