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

发布于 2024-09-17 21:47:23 字数 500 浏览 4 评论 0原文

有大量的反射示例,允许您获取:

  1. 类中的所有属性
  2. 单个属性,前提是您知道字符串名称

有没有办法(使用反射、TypeDescriptor 或其他方式)获取字符串名称运行时类中的属性,假设我拥有的只是该类和属性的实例?

我有一个类的实例,其中包含我想要获取其字符串名称(而不是 getter/setter)的属性(以及其他属性)。我需要使用反射对该属性做一些工作,但不想使用硬编码字符串名称维护代码,以防我重构属性名称。因此,我想以编程方式获取属性的名称。

我知道我可以使用反射轻松获取类中的所有属性,然后获取每个属性的名称。我要求的是一个为我提供属性名称的函数,前提是我将属性的实例传递给它。换句话说,如何从 class.GetType().GetProperty(myProperty) 返回给我的 PropertyInfo[] 数组中找到我想要的属性,以便我可以从中获取PropertyInfo.Name吗?

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

  1. All properties in a class
  2. A single property, provided you know the string name

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?

I have an instance of the class with the property (as well as other properties) that I want to get the string name of (not the getter/setter). I need to do some work on that property using Reflection, but don't want to maintain code with hardcoded string names in case I refactor the property name. Thus, I want to programatically get the name of the property.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

夜深人未静 2024-09-24 21:47:23

如果您已有 PropertyInfo,则 @dtb 使用 PropertyInfo.Name 的答案是正确的方法。但是,如果您想找出当前所在的属性代码,则必须遍历当前调用堆栈以找出当前正在执行的方法并从中派生属性名称。

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

如果您没有 PropertyInfo 对象,您可以从属性 表达式 中获取该对象,如下所示:

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

要使用它,您需要编写如下内容:

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

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

If you don't have a PropertyInfo object, you can get that from a property expression, 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"
遗弃M 2024-09-24 21:47:23

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

With C# 6.0 (Visual Studio 2015), you can now use the nameof operator, like this:

var obj = new MyObject();
string propertyName = nameof(obj.Property);
string methodName = nameof(obj.Method);
string directPropertyName = nameof(MyObject.Property);
string directMethodName = nameof(MyObject.Method);
月寒剑心 2024-09-24 21:47:23

如果有人需要它......这里是答案的 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

用法:

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

In case anyone needs it...here is the VB .NET version of the answer:

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)
耶耶耶 2024-09-24 21:47:23

我想将 TKTS 的答案 语法转换为 C# :

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

该代码的用法如下:

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

当所有属性都为空值时,可能会发生异常,所以在实现该代码时需要小心。

I want to convert TKTS' answer syntax to 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);

An exception could happen when all properties have null values, so care is needed when implementing this code.

安静 2024-09-24 21:47:23

Jacob 提供的版本有时会因强制转换无效而出现异常。此版本解决了该转换问题:

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

The version provided by Jacob sometimes gives an exception due to the cast being invalid. This version solves that casting 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;
    }
一百个冬季 2024-09-24 21:47:23

myClassInstance.GetType().GetProperties() 为您提供 myClassInstance 类型的所有公共属性的 PropertyInfo 实例。 (有关文档和其他重载,请参阅 MSDN。) “PropertyInfo.Name”是属性的实际名称。如果您已经知道属性的名称,请使用 GetProperty(name) 检索其 PropertyInfo 对象(请参阅 MSDN 再次)。

myClassInstance.GetType().GetProperties() gives you PropertyInfo instances for all public properties for myClassInstance's type. (See MSDN for documentation and other overloads.) ´PropertyInfo.Name´ is the actual name of the property. In case you already know the name of the property use GetProperty(name) to retrieve its PropertyInfo object (see MSDN again).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文