c# - 获取通用的自定义属性

标签 c# generics reflection attributes

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

[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"

我唯一能做的就是为我的属性生成一个循环,但我需要通知我的 typeof 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);
    }
}

有什么办法可以按照我想要的方式去做吗?

最佳答案

你不能完全按照你所展示的那样做,因为 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));
}

关于c# - 获取通用的自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20342041/

相关文章:

java - 反射运行时性能 - Java 与 CLR

Java:Java 是否在幕后将方法参数转换为数组?

c# - Cosmos,在 MessageController 中检索对话数据

c# - Visual Studio Code 中的 MVC 6 无法识别 ViewModel

swift - 在 Swift 中更新不同数据类型属性的通用方法

java - Java 语法中用于区分 >>(右移运算符)与嵌套泛型 List<List<String>> 的技巧

从类型到类的 Java 泛型

c# - 具有行和列标题WPF的ItemsControl

c# - 可以连接到命名管道的客户端数

java - 通用列表中的唯一类