【问题标题】:Custom Attribute on property in C# [duplicate]C#中属性的自定义属性[重复]
【发布时间】:2016-02-10 12:22:11
【问题描述】:

我有一个类 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

是否有可能完成这项任务? 有人可以建议我一个方法吗? 最好的祝福 棒棒哒

【问题讨论】:

标签: c# reflection custom-properties


【解决方案1】:

.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;

【讨论】:

  • 好吧,考虑到 nameof 仅从 C# 6.0 开始可用。
  • @Alexey 我确实使用了“也许”这个词;)
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 2017-05-31
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多