无法获取DisplayAttribute名称
问题描述:
我有一个从EF4生成的部分类,我分配了一个MetadataType
以便在ASP.NET MVC3窗体上显示控件的名称,并且按预期工作。无法获取DisplayAttribute名称
我想使用分配给每个属性的相同DisplayAttribute
来检索属性的显示Name
值以用于其他目的。我的课是这样的:
using Domain.Metadata;
namespace Domain
{
[MetadataType(typeof(ClassAMetada))]
public partial class ClassA
{}
}
namespace Domain.Metadata
{
public class ClassAMetada
{
[Display(Name = "Property 1 Description", Order = 1)]
public Boolean Property1;
[Display(Name = "Property 2 Description", Order = 2)]
public Boolean Property2;
}
}
我已经看到了这3个员额,并试图提出解决方案:
- How to get DisplayAttribute of a property by Reflection?
- C# Buddy Classes/Meta Data and Reflection
- Get [DisplayName] attribute of a property in strongly-typed way
但没有他们可以获取属性Name
va略;该属性未找到,因此是null
,所以它返回一个空字符串(第三个问题)或属性名称(第一个问题);为了发现属性,第二个问题略有改变,但结果也是一个空字符串。
你能帮我这个吗?非常感谢!
编辑:
这里是2种方法我使用中检索的属性值(包括工作分开)的代码。两者非常相似:第一个使用带有属性名称的字符串,另一个使用lamba表达式。
private static string GetDisplayName(Type dataType, string fieldName)
{
DisplayAttribute attr;
attr = (DisplayAttribute)dataType.GetProperty(fieldName).GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault();
if (attr == null)
{
MetadataTypeAttribute metadataType = (MetadataTypeAttribute)dataType.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault();
if (metadataType != null)
{
var property = metadataType.MetadataClassType.GetProperty(fieldName);
if (property != null)
{
attr = (DisplayAttribute)property.GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault();
}
}
}
return (attr != null) ? attr.Name : String.Empty;
}
private static string GetPropertyName<T>(Expression<Func<T>> expression)
{
MemberExpression propertyExpression = (MemberExpression)expression.Body;
MemberInfo propertyMember = propertyExpression.Member;
Object[] displayAttributes = propertyMember.GetCustomAttributes(typeof(DisplayAttribute), true);
if (displayAttributes != null && displayAttributes.Length == 1)
return ((DisplayAttribute)displayAttributes[0]).Name;
return propertyMember.Name;
}
答
您是否考虑将显示名称放入资源中?比所有这些反射魔术更容易重用。
你可以简单地做:
[Display(Name = "Property1Name", ResourceType = typeof(Resources), Order = 1)]
public Boolean Property1;
并添加Resources.resx
文件到您的项目与Property1Name
键和“财产1所描述”值。当然,您可能必须将默认资源访问权限从internal
设置为public
。
后来,在其他地方,你需要这些字符串只需拨打:
string displayName = Domain.Resources.Property1Name;
我删除了我的答案,因为我怕我带领你走向错误的路线。你可以发布代码显示你如何尝试检索'Name'属性? – 2011-04-27 10:45:44
@Sergi Papaseit:好的,没问题;)我用我用来检索属性值的方法代码更新了我的问题。谢谢您的帮助! – jmpcm 2011-04-27 10:53:59