获取一个字段的名称在C# [英] Getting the name of a field in c#

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

问题描述

由于这个类:

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



我如何能够提取的名称 MyField的中的代码?

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

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 field?

究其原因,问题是,我想这个特殊的代码是反对的名字refactorizations性。

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 fieldname. I have some stuff that is using a string representation of the field 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天全站免登陆