获取DisplayName属性的值

Bas*_*ata 65 c# attributes

public class Class1
{
    [DisplayName("Something To Name")]
    public virtual string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

如何在C#中获取DisplayName属性的值?

Ric*_*ebb 78

尝试我的这些实用方法:

using System.ComponentModel;
using System.Globalization;
using System.Linq;


public static T GetAttribute<T>(this MemberInfo member, bool isRequired)
    where T : Attribute
{
    var attribute = member.GetCustomAttributes(typeof(T), false).SingleOrDefault();

    if (attribute == null && isRequired)
    {
        throw new ArgumentException(
            string.Format(
                CultureInfo.InvariantCulture, 
                "The {0} attribute must be defined on member {1}", 
                typeof(T).Name, 
                member.Name));
    }

    return (T)attribute;
}

public static string GetPropertyDisplayName<T>(Expression<Func<T, object>> propertyExpression)
{
    var memberInfo = GetPropertyInformation(propertyExpression.Body);
    if (memberInfo == null)
    {
        throw new ArgumentException(
            "No property reference expression was found.",
            "propertyExpression");
    }

    var attr = memberInfo.GetAttribute<DisplayNameAttribute>(false);
    if (attr == null)
    {
        return memberInfo.Name;
    }

    return attr.DisplayName;
}

public static MemberInfo GetPropertyInformation(Expression propertyExpression)
{
    Debug.Assert(propertyExpression != null, "propertyExpression != null");
    MemberExpression memberExpr = propertyExpression as MemberExpression;
    if (memberExpr == null)
    {
        UnaryExpression unaryExpr = propertyExpression as UnaryExpression;
        if (unaryExpr != null && unaryExpr.NodeType == ExpressionType.Convert)
        {
            memberExpr = unaryExpr.Operand as MemberExpression;
        }
    }

    if (memberExpr != null && memberExpr.Member.MemberType == MemberTypes.Property)
    {
        return memberExpr.Member;
    }

    return null;
}
Run Code Online (Sandbox Code Playgroud)

用法是:

string displayName = ReflectionExtensions.GetPropertyDisplayName<SomeClass>(i => i.SomeProperty);
Run Code Online (Sandbox Code Playgroud)

  • @rich-tebb 当你有 [Display(Name = "SomeProperty", ResourceType = typeof(SomeResource))] 时,这似乎不起作用,它不返回本地化名称。会尝试修改它,这样就可以了。 (2认同)

Jon*_*eet 30

您需要获取PropertyInfo与属性相关联(例如,通过typeof(Class1).GetProperty("Name")),然后调用GetCustomAttributes.

由于返回多个值,它有点混乱 - 如果您需要从几个地方需要它,您可能想要编写一个帮助方法来执行此操作.(在某个框架中可能已经有一个帮助方法,但是如果有我不知道的话.)

编辑:由于leppie指出的那样,这样的方法:Attribute.GetCustomAttribute(MemberInfo, Type)

  • 我们得到了`Attribute.GetCustomAttribute(MemberInfo,Type)`:) http://msdn.microsoft.com/en-us/library/ms130863 (18认同)
  • @cesAR:您已经发布了返回*此*问题的链接。但一般情况下请不要这样做 - 在链接到另一个问题的一个答案上留下评论几乎是不合适的。 (2认同)

R. *_*des 28

首先,您需要获取MemberInfo表示该属性的对象.你需要做一些反思:

MemberInfo property = typeof(Class1).GetProperty("Name");
Run Code Online (Sandbox Code Playgroud)

(我正在使用"旧式"反射,但如果您在编译时可以访问该类型,也可以使用表达式树)

然后,您可以获取属性并获取属性的值DisplayName:

var attribute = property.GetCustomAttributes(typeof(DisplayNameAttribute), true)
      .Cast<DisplayNameAttribute>().Single();
string displayName = attribute.DisplayName;
Run Code Online (Sandbox Code Playgroud)

()括号是必需的拼写错误

  • 如果displayNameAttribute为null,则会失败.而不是返回单个尝试返回FirstOrDefault()然后检查此值是否为null. (3认同)

Luk*_*ett 12

从具有Class1的视图中,因为它是强类型视图模型:

ModelMetadata.FromLambdaExpression<Class1, string>(x => x.Name, ViewData).DisplayName;
Run Code Online (Sandbox Code Playgroud)


Mat*_*cic 12

如果有人有兴趣使用DisplayAttributeResourceType从属性获取本地化字符串,如下所示:

[Display(Name = "Year", ResourceType = typeof(ArrivalsResource))]
public int Year { get; set; }
Run Code Online (Sandbox Code Playgroud)

之后使用以下内容displayAttribute != null(如上面@alex'答案所示):

ResourceManager resourceManager = new ResourceManager(displayAttribute.ResourceType);
var entry = resourceManager.GetResourceSet(Thread.CurrentThread.CurrentUICulture, true, true)
                           .OfType<DictionaryEntry>()
                           .FirstOrDefault(p => p.Key.ToString() == displayAttribute.Name);

return entry.Value.ToString();
Run Code Online (Sandbox Code Playgroud)

  • `DisplayAttribute`有`GetName`方法.不需要.NET 4+中的代码:https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute.getname%28v=vs.110%29.aspx (5认同)

小智 7

Rich Tebb的精彩课程!我一直在使用DisplayAttribute,代码对我不起作用.我唯一添加的是处理DisplayAttribute.简短的搜索产生了这个属性对于MVC3和.Net 4来说是新的,并且几乎完全相同.这是该方法的修改版本:

 public static string GetPropertyDisplayString<T>(Expression<Func<T, object>> propertyExpression)
    {
        var memberInfo = GetPropertyInformation(propertyExpression.Body);
        if (memberInfo == null)
        {
            throw new ArgumentException(
                "No property reference expression was found.",
                "propertyExpression");
        }

        var displayAttribute = memberInfo.GetAttribute<DisplayAttribute>(false);

        if (displayAttribute != null)
        {
            return displayAttribute.Name;
        }
        else
        {
            var displayNameAttribute = memberInfo.GetAttribute<DisplayNameAttribute>(false);
            if (displayNameAttribute != null)
            {
                return displayNameAttribute.DisplayName;
            }
            else
            {
                return memberInfo.Name;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)


小智 5

var propInfo = typeof(Class1).GetProperty("Name");
var displayNameAttribute = propInfo.GetCustomAttributes(typeof(DisplayNameAttribute), false);
var displayName = displayNameAttribute[0] as DisplayNameAttribute).DisplayName;
Run Code Online (Sandbox Code Playgroud)

displayName 变量现在保存属性的值。