获取自定义属性Generic

时间:2013-12-03 02:59:26

标签: c# generics reflection attributes

我正在创建自定义属性。我将在多个类中使用它:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class Display : System.Attribute
{
    public string Name { get; set; }

    public string Internal { get; set; }

}

public class Class1
{
    [Display(Name = "ID")]
    public int ID { get; set; }

    [Display(Name = "Name")]
    public string Title { get; set; }
}

public class Class2
{
    [Display(Name = "ID")]
    public int ID { get; set; }

    [Display(Name = "Name")]
    public string Title { get; set; }
}

这里工作正常,但我希望尽可能通用,比如MVC示例:

Class1 class1 = new Class1();
class1.Title.DisplayName () / / returns the value "Name"

我唯一能做的就是生成我的属性循环,但我需要通知我的classof Class1

foreach (var prop in typeof(Class1).GetProperties())
{
    var attrs = (Display[])prop.GetCustomAttributes(typeof(Display), false);
    foreach (var attr in attrs)
    {
        Console.WriteLine("{0}: {1}", prop.Name, attr.Name);
    }
}

有没有办法以我想要的方式去做?

1 个答案:

答案 0 :(得分:5)

您无法完全按照自己的显示进行操作,因为class1.Title是一个计算结果为字符串的表达式。您正在寻找有关Title属性的元数据。您可以使用表达式树来写一些接近的东西。这是一个简短的帮助器类,它从属性表中提取属性值:

public static class PropertyHelper
{
    public static string GetDisplayName<T>(Expression<Func<T, object>> propertyExpression)
    {
        Expression expression;
        if (propertyExpression.Body.NodeType == ExpressionType.Convert)
        {
            expression = ((UnaryExpression)propertyExpression.Body).Operand;
        }
        else
        {
            expression = propertyExpression.Body;
        }

        if (expression.NodeType != ExpressionType.MemberAccess)
        {
            throw new ArgumentException("Must be a property expression.", "propertyExpression");
        }

        var me = (MemberExpression)expression;
        var member = me.Member;
        var att = member.GetCustomAttributes(typeof(DisplayAttribute), false).OfType<DisplayAttribute>().FirstOrDefault();
        if (att != null)
        {
            return att.Name;
        }
        else
        {
            // No attribute found, just use the actual name.
            return member.Name;
        }
    }

    public static string GetDisplayName<T>(this T target, Expression<Func<T, object>> propertyExpression)
    {
        return GetDisplayName<T>(propertyExpression);
    }
}

这是一些示例用法。请注意,您甚至不需要实例来获取此元数据,但我已经包含了一个可能很方便的扩展方法。

public static void Main(string[] args)
{
    Class1 class1 = new Class1();
    Console.WriteLine(class1.GetDisplayName(c => c.Title));
    Console.WriteLine(PropertyHelper.GetDisplayName<Class1>(c => c.Title));
}