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#如何在字符串中获取属性名称?

更新1

在Christian Hayter的帮助下,我可以使用:

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

要么

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

如果有人有其他想法而无需创建新对象。 随意分享:)谢谢。

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

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

然后你可以像这样调用它:

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

请注意,由于您没有读取属性值,因此该类的任何实例都将执行此操作。

(那些不是参数btw,它们是属性。)

嗯,一个选择是使用代表。 例如:

 public class SelectList { public SelectList(IEnumerable source, Func idProjection, Func displayProjection) { ... } } 

然后:

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

var name = (string) typeof(TimeZone).GetProperty("DisplayName").GetValue(0);

 string id=typeof(TimeZone).GetProperties()[0].Name; string displayName=typeof(TimeZone).GetProperties()[1].Name; var gmtList = new SelectList( repository.GetSystemTimeZones(), id, displayName); 

这将起作用,除非声明的id和displayname的顺序不会改变。 或者您可以考虑为属性定义属性以区分id和displayname。

从C#6.0开始,您现在可以使用了

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