C# 中 属性 的自定义属性

Custom Attribute on property in C#

我有一个 class 人有两个属性

public sealed class Person
{
[Description("This is the first name")]
public string FirstName { get; set; }
[Description("This is the last name")]
public string LastName { get; set; }
}

在我的控制台应用程序代码中,我想为每个实例的每个 属性 获取描述属性的值......

类似于

的内容
Person myPerson = new Person();
myPerson.LastName.GetDescription() // method to retrieve the value of the attribute

这个任务可以做吗? 有人可以建议我一种方法吗? 最好的祝福 很棒

使用完全相同的语法是不可能的。可以通过使用表达式树...例如:

public static class DescripionExtractor 
{
    public static string GetDescription<TValue>(Expression<Func<TValue>> exp) 
    {
        var body = exp.Body as MemberExpression;

        if (body == null) 
        {
            throw new ArgumentException("exp");
        }

        var attrs = (DescriptionAttribute[])body.Member.GetCustomAttributes(typeof(DescriptionAttribute), true);

        if (attrs.Length == 0) 
        {
            return null;
        }

        return attrs[0].Description;
    }
}

然后:

Person person = null;
string desc = DescripionExtractor.GetDescription(() => person.FirstName);

请注意,person 的值无关紧要。它可以是 null 并且一切都会正常工作,因为 person 并没有真正被访问。只有它的类型很重要。

.LastName returns 一个字符串,所以你不能从那里做很多事情。最终,您需要 PropertyInfo 为此。有两种获取方式:

  • 通过 Expression(可能 SomeMethod<Person>(p => p.LastName)
  • 来自 string(可能来自 nameof

例如,您可以做如下事情:

var desc = Helper.GetDescription<Person>(nameof(Person.LastName));

var desc = Helper.GetDescription(typeof(Person), nameof(Person.LastName));

类似:

var attrib = (DescriptionAttribute)Attribute.GetCustomAttribute(
    type.GetProperty(propertyName), typeof(DescriptionAttribute));
return attrib?.Description;