获取使用属性反映字符串名称 [英] Get string name of property using reflection

查看:151
本文介绍了获取使用属性反映字符串名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有反射的例子在那里,让你得到一个整体的财富之一:

There is a whole wealth of reflection examples out there that allow you to get either:


    1。在类的所有属性。

    1. All properties in a class

2。一个单一的财产,只要你知道字符串名称

2. A single property, provided you know the string name

有没有(使用反射,TypeDescriptor,或以其他方式)来获得在运行时的类属性的字符串名称,提供一切我是类和属性的实例?

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?

修改
我知道我可以使用反射很容易地得到一个类的所有属性,然后获得每个属性的名称。就是我要求的是给我一个属性名称的函数,只要我通过它的属性的实例。换句话说,我怎么找物业我想从的PropertyInfo []数组从class.GetType()退还给我。的getProperty(myProperty的),这样​​我可以从它那里得到的PropertyInfo.Name?

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?

推荐答案

如果您已经有一个的PropertyInfo ,然后@ DTB的答案是正确的。但是,如果你想找出哪些财产的code你目前在,你就必须遍历当前调用堆栈,找出你正在执行哪种方法,并从那里获得的属性名

If you already have a PropertyInfo, then @dtb's answer is the right one. 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);

编辑:

你的澄清后,我想知道,如果你想要做的是从属性得到属性的名称的前pression 的。如果是这样,你可能会想要写一个方法是这样的:

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"

这篇关于获取使用属性反映字符串名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆