简体   繁体   English

使用反射获取属性的字符串名称

[英]Get string name of property using reflection

There is a whole wealth of reflection examples out there that allow you to get either: 那里有大量的反思例子可以让你得到:

    1. All properties in a class 1.班级中的所有属性

    2. A single property, provided you know the string name 2.单个属性,前提是您知道字符串名称

Is there a way (using reflection, TypeDescriptor, or otherwise) to get the string name of a property in a class at runtime, provided all I have is an instance of the class and property? 有没有办法(使用反射,TypeDescriptor或其他方法)在运行时获取类中属性的字符串名称,前提是我拥有​​的是类和属性的实例?

EDIT I know that I can easily get all the properties in a class using reflection and then get the name of each property. 编辑我知道我可以使用反射轻松获取类中的所有属性,然后获取每个属性的名称。 What I'm asking for is a function to give me name of a property, provided I pass it the instance of the property. 我要求的是一个函数来给我一个属性的名称,前提是我传递了属性的实例。 In other words, how do I find the property I want from the PropertyInfo[] array returned to me from the class.GetType().GetProperty(myProperty) so that I can get the PropertyInfo.Name from it? 换句话说,如何从class.GetType()。GetProperty(myProperty)中找到PropertyInfo []数组返回给我的属性,以便从中获取PropertyInfo.Name?

If you already have a PropertyInfo , then @dtb's answer is the right one. 如果您已经拥有PropertyInfo ,那么@ dtb的答案是正确的。 If, however, you're wanting to find out which property's code you're currently in, you'll have to traverse the current call stack to find out which method you're currently executing and derive the property name from there. 但是,如果您想要找出当前所在的属性代码,则必须遍历当前的调用堆栈以找出当前正在执行的方法,并从那里派生属性名称。

var stackTrace = new StackTrace();
var frames = stackTrace.GetFrames();
var thisFrame = frames[0];
var method = thisFrame.GetMethod();
var methodName = method.Name; // Should be get_* or set_*
var propertyName = method.Name.Substring(4);

Edit: 编辑:

After your clarification, I'm wondering if what you're wanting to do is get the name of a property from a property expression . 在您澄清之后,我想知道您想要做的是从属性表达式获取属性的名称。 If so, you might want to write a method like this: 如果是这样,您可能想要编写如下方法:

public static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
    return (propertyExpression.Body as MemberExpression).Member.Name;
}

To use it, you'd write something like this: 要使用它,你会写这样的东西:

var propertyName = GetPropertyName(
    () => myObject.AProperty); // returns "AProperty"

With C# 6.0 (Visual Studio 2015), you can now use the nameof operator, like this: 使用C#6.0(Visual Studio 2015),您现在可以使用nameof运算符,如下所示:

var obj = new MyObject();
string propertyName = nameof(obj.Property);
string methodName = nameof(obj.Method);
string directPropertyName = nameof(MyObject.Property);
string directMethodName = nameof(MyObject.Method);

In case anyone needs it...here is the VB .NET version of the answer: 如果有人需要它...这里是答案的VB .NET版本:

Public Shared Function GetPropertyName(Of t)(ByVal PropertyExp As Expression(Of Func(Of t))) As String
   Return TryCast(PropertyExp.Body, MemberExpression).Member.Name
End Function

Usage: 用法:

Dim name As String = GetPropertyName(Function() (New myObject).AProperty)

acutully the right answer which is written by TKTS, and here I just want to convert his syntax to C# acutully是TKTS编写的正确答案,在这里我只想将他的语法转换为C#

public static string GetPropertyName<t>(Expression<Func<t>> PropertyExp)
{
return (PropertyExp.Body as MemberExpression).Member.Name;
}

and the usage of this code goes like the example as below: 并且此代码的​​用法如下所示:

string name = GetPropertyName(() => (new Tasks()).Title);

in addition : there is an exception could be happen that when the comes with all properties has null values, so anybody has to take this on his concentration when hes implementing his code 另外:有一个例外可能会发生,当所有属性都带有空值时,所以任何人都必须在他实现他的代码时集中注意力

Thanks TKTS .. 谢谢TKTS ..

I used the version provided by Jacob but sometimes it gave an exception. 我使用了雅各布提供的版本,但有时它给了一个例外。 It was because the cast was invalid. 这是因为演员阵容无效。 This version solved the issue: 这个版本解决了这个问题:

    public static string GetPropertyName<T>(this Expression<Func<T>> propertyExpression)
    {
        ConstantExpression cExpr = propertyExpression.Body as ConstantExpression;
        MemberExpression mExpr = propertyExpression.Body as MemberExpression;

        if (cExpr != null)
            return cExpr.Value.ToString();
        else if (mExpr != null)
            return mExpr.Member.Name;

        else return null;
    }

myClassInstance.GetType().GetProperties() gives you PropertyInfo instances for all public properties for myClassInstance 's type. myClassInstance.GetType().GetProperties()myClassInstance类型的所有公共属性提供PropertyInfo实例。 (See MSDN for documentation and other overloads.) ´PropertyInfo.Name´ is the actual name of the property. (有关文档和其他重载,请参阅MSDN 。)'PropertyInfo.Name'是属性的实际名称。 In case you already know the name of the property use GetProperty(name) to retrieve its PropertyInfo object (see MSDN again). 如果您已经知道属性的名称,请使用GetProperty(name)来检索其PropertyInfo对象(请再次参阅MSDN )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM