在C#中获取属性的名称 [英] Getting the name of a property in c#

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

问题描述

提供此类:

public class MyClass
{
    public int MyProperty {get; set;}
}

如何在代码中提取 MyProperty 的名称?

How will I be able to extract the name of MyProperty in code?

例如,我能够获得这样的类的名称

For example, I am able to get the name of the class like this

typeof(MyClass).Name

如何为该物业做类似的事情?

How can I do something similar for the property?

这个问题的原因是我希望这个特定的代码能够抵抗名称的重构.

The reason for the question is that I want this particular code to be resistant against refactorizations of the names.

具有抗性,我的意思是我希望面对属性名称的更改,调用站点上的代码要健壮.我有一些使用属性名称的字符串表示形式的东西.对不起,措辞不好.我没有包含呼叫站点代码是为了保持问题的清洁度,并且没有使您陷入有关呼叫站点代码性质的其他讨论中.

With resistant I mean that I want the code at the call site to be robust in the face of changes of the propertyname. I have some stuff that is using a string representation of the property name. Sorry for the poor phrasing. I did not include call site code in order to keep the problem clean and not wander off into other discussions on the nature of the call site code.

推荐答案

您可以使用编译器生成的表达式树来做到这一点:

You do it like this, using compiler generated expression trees:

public static string GetMemberName<T, TValue>(Expression<Func<T, TValue>> memberAccess)
{
    return ((MemberExpression)memberAccess.Body).Member.Name;
}

现在从代码中调用静态方法:

Now call the static method from code:

class MyClass
{
    public int Field;
    public string Property { get; set; }
}

var fieldName = GetMemberName((MyClass c) => c.Field);
var propertyName = GetMemberName((MyClass c) => c.Property);
// fieldName has string value of `Field`
// propertyName has string value of `Property`

您现在还可以使用重构来重命名该字段,而无需破坏此代码

You can now also use refactoring to rename that field without breaking this code

这篇关于在C#中获取属性的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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