【发布时间】:2013-08-09 09:14:58
【问题描述】:
我正在开发一个 ASP.net MVC4 网站,并拥有模型和视图模型层。 由于某些原因我对 Model 和 ViewModel 中的几个属性有不同的名称
型号
public partial class Project
{
public string Desc {get; set;}
}
查看模型
public class ProjectViewModel
{
public string Description { get; set; }
}
现在在模型层,如果属性不同,我需要使用 ViewModel 名称。我正在考虑创建一个自定义属性,以便我可以在模型中拥有这样的东西:
public partial class Project
{
[ViewModelPropertyName("Description")]
public string Desc {get;set;}
}
并在模型层使用它作为
string.Format("ViewModel Property Name is {0}", this.Desc.ViewModelPropertyName())
我希望它是通用的,这样如果属性上没有ViewModelPropertyName 属性,那么它应该返回相同的属性名称,即如果Desc 属性没有属性,那么它应该只返回"Desc"。
这是我尝试过的
public class ViewModelPropertyNameAttribute : System.Attribute
{
#region Fields
string viewModelPropertyName;
#endregion
#region Properties
public string GetViewModelPropertyName()
{
return viewModelPropertyName;
}
#endregion
#region Constructor
public ViewModelPropertyNameAttribute(string propertyName)
{
this.viewModelPropertyName = propertyName;
}
#endregion
}
需要有关如何访问自定义属性的帮助
当前状态
public static class ModelExtensionMethods
{
public static string ViewModelPropertyName(this Object obj)
{
// ERROR: Cannot convert from 'object' to 'System.Reflect.Assembly'
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(obj);
foreach (System.Attribute attr in attrs)
{
if (attr is ViewModelPropertyNameAttribute)
{
return ((ViewModelPropertyNameAttribute)attr).GetViewModelPropertyName();
}
}
return string.Empty;
}
}
但这有编译时错误:
【问题讨论】:
-
this.Desc.ViewModelPropertyName必须是this.Desc.GetViewModelPropertyName()。没有extension property这样的东西。
标签: c# c#-4.0 reflection extension-methods custom-attributes