在mvc3服务器端代码上获取显示注释值

有没有办法在服务器端代码中获取注释的值? 例如,我有:

public class Dummy { [Display(Name = "Foo")] public string foo { get; set; } [Display(Name = "Bar")] public string bar { get; set; } } 

我希望能够在服务器端获得值“Foo”而不将其发布回页面,但是像类的属性或类似的东西。 就像@ Html.LabelFor(model => model.Foo)但是在c#服务器代码中。

那可能吗?

谢谢。

像这样的东西?

 string displayName = GetDisplayName((Dummy x) => x.foo); // ... public static string GetDisplayName(Expression> exp) { var me = exp.Body as MemberExpression; if (me == null) throw new ArgumentException("Must be a MemberExpression.", "exp"); var attr = me.Member .GetCustomAttributes(typeof(DisplayAttribute), false) .Cast() .SingleOrDefault(); return (attr != null) ? attr.Name : me.Member.Name; } 

或者,如果您希望能够针对实例调用该方法并利用类型推断:

 var dummy = new Dummy(); string displayName = dummy.GetDisplayName(x => x.foo); // ... public static string GetDisplayName(this T src, Expression> exp) { var me = exp.Body as MemberExpression; if (me == null) throw new ArgumentException("Must be a MemberExpression.", "exp"); var attr = me.Member .GetCustomAttributes(typeof(DisplayAttribute), false) .Cast() .SingleOrDefault(); return (attr != null) ? attr.Name : me.Member.Name; } 

你需要使用reflection。 这是一个示例控制台程序,可以执行您想要的操作。

 class Program { static void Main(string[] args) { Dummy dummy = new Dummy(); PropertyInfo[] properties = dummy.GetType().GetProperties(); foreach (PropertyInfo property in properties) { IEnumerable displayAttributes = property.GetCustomAttributes(typeof(DisplayAttribute), false).Cast(); foreach (DisplayAttribute displayAttribute in displayAttributes) { Console.WriteLine("Property {0} has display name {1}", property.Name, displayAttribute.Name); } } Console.ReadLine(); } } public class Dummy { [Display(Name = "Foo")] public string foo { get; set; } [Display(Name = "Bar")] public string bar { get; set; } } 

这将产生以下结果:

http://sofzh.miximages.com/c%23/reflectresult.jpg