获取mvc3服务器端代码上的显示注释值
本文关键字:显示 注释 mvc3 服务器端 代码 获取 | 更新日期: 2023-09-27 18:05:33
是否有办法在服务器端代码中获得注释的值?例如,我有:
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<T, U>(Expression<Func<T, U>> 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<DisplayAttribute>()
.SingleOrDefault();
return (attr != null) ? attr.Name : me.Member.Name;
}
或者,如果您希望能够针对实例调用该方法并利用类型推断:
var dummy = new Dummy();
string displayName = dummy.GetDisplayName(x => x.foo);
// ...
public static string GetDisplayName<T, U>(this T src, Expression<Func<T, U>> 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<DisplayAttribute>()
.SingleOrDefault();
return (attr != null) ? attr.Name : me.Member.Name;
}
您将需要使用反射。下面是一个示例控制台程序,可以满足您的要求。
class Program
{
static void Main(string[] args)
{
Dummy dummy = new Dummy();
PropertyInfo[] properties = dummy.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
IEnumerable<DisplayAttribute> displayAttributes = property.GetCustomAttributes(typeof(DisplayAttribute), false).Cast<DisplayAttribute>();
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://www.codetunnel.com/content/images/reflectresult.jpg