0

我有一个类 Person 有两个属性

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

有可能完成这个任务吗?有人可以建议我一个方法吗?最好的问候 Fab

4

2 回答 2

3

返回一个字符串,.LastName所以你不能从那里做很多事情。最终,你需要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;
于 2016-02-10T12:27:20.150 回答
0

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

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没有真正访问过。只有它的类型很重要。

于 2016-02-10T12:27:04.957 回答