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

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

问题描述

有大量的反射示例可以让您获得:

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?

编辑我知道我可以使用反射轻松获取类中的所有属性,然后获取每个属性的名称.我要的是一个函数,它可以给我一个属性的名称,前提是我将属性的实例传递给它.换句话说,我如何从从 class.GetType().GetProperty(myProperty) 返回给我的 PropertyInfo[] 数组中找到我想要的属性,以便我可以从中获取 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 的答案 是正确的.但是,如果您想找出当前所在的属性代码,则必须遍历当前调用堆栈以找出当前正在执行的方法并从中派生属性名称.

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);

在您澄清之后,我想知道您是否想要从属性表达式中获取属性的名称.如果是这样,你可能想写一个这样的方法:

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天全站免登陆