C#如何获取类属性的名称(以字符串形式)? [英] C# how to get the name (in string) of a class property?

查看:129
本文介绍了C#如何获取类属性的名称(以字符串形式)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class TimeZone
{
    public int Id { get; set; }
    public string DisplayName{ get; set; }
}

我在其他班级:

   var gmtList = new SelectList(
       repository.GetSystemTimeZones(), 
       "Id",
       "DisplayName");

注意:System.Web.Mvc.SelectList

我不希望必须使用"Id"和"DisplayName"来写属性名称.稍后,属性名称可能会更改,并且编译器将不会检测到此错误.C#如何获取字符串中的属性名称?

I do not like to have to write the property name with "Id" and "DisplayName". Later in time, maybe the property name will change and the compiler will not detect this error. C# how to get property name in a string?

更新1

在克里斯蒂安·海特(Christian Hayter)的帮助下,我可以使用:

With the help of Christian Hayter, I can use:

var tz = new TimeZone();
var gmtList = new SelectList(
    repository.GetSystemTimeZones(), 
    NameOf(() => tz.Id), 
    NameOf(() => tz.TranslatedName));

OR

var gmtList = new SelectList(
    repository.GetSystemTimeZones(), 
    NameOf(() => new TimeZone().Id), 
    NameOf(() => new TimeZone().TranslatedName));

如果某人有其他想法,而无需创建新对象.随时分享:)谢谢.

If someone has other idea without the need of creating a new object. Feel free to share it :) thank you.

推荐答案

您可以创建一个实用程序方法来从表达式树中提取属性名称,如下所示:

You could create a utility method to extract the property name from an expression tree, like this:

string NameOf<T>(Expression<Func<T>> expr) {
    return ((MemberExpression) expr.Body).Member.Name;
}

然后您可以这样称呼它:

Then you can call it like this:

var gmtList = new SelectList(repository.GetSystemTimeZones(),
    NameOf(() => tz.Id),
    NameOf(() => tz.DisplayName));

请注意,该类的任何实例都可以使用,因为您不是在读取属性值,而只是在读取名称.

Note that any instance of the class will do, since you are not reading the property value, only the name.

这篇关于C#如何获取类属性的名称(以字符串形式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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