【问题标题】:Get custom attributes from an object从对象获取自定义属性
【发布时间】:2012-06-08 10:27:30
【问题描述】:

当我尝试从object 获取自定义属性时,该函数返回null。为什么?

class Person
{
    [ColumnName("first_name")]
    string FirstName { get; set; }

    Person()
    {
        FirstName = "not important";
        var attrs = AttributeReader.Read(FirstName);
    }
}

static class AttributeReader
{
    static object[] Read(object column)
    {
        return column.GetType().GetCustomAttributes(typeof(ColumnNameAttribute), false);
    }
}

【问题讨论】:

  • 您尝试公开 FirstName 吗?
  • 代码只是我正在尝试做的一个通用示例。
  • 你不是要打电话给var attrs = AttributeReader.Read(Person);,而不是var attrs = AttributeReader.Read(FirstName);吗?

标签: c# reflection attributes custom-attributes


【解决方案1】:

您正在将string"not important" 传递给该方法。因此Typetypeof(string)。哪个没有这些属性。此外,即使Person 也没有该属性:只有MemberInfo (FirstName) 拥有它们。

通过传递Expression 可以做到这一点:

public static ColumnNameAttribute[] Read<T>(Expression<Func<T>> func)
{
    var member = func.Body as MemberExpression;
    if(member == null) throw new ArgumentException(
         "Lambda must resolve to a member");
    return (ColumnNameAttribute[])Attribute.GetCustomAttributes(
         member.Member, typeof(ColumnNameAttribute), false);
}

var attrs = AttributeReader.Read(() => FirstName);

但是!我应该建议我不确定 Person 构造函数是否适合这个。可能需要缓存。

如果您不想使用 lambda,则传递 Type 和成员名称也可以,即

var attrs = AttributeReader.Read(typeof(Person), "FirstName");

(并从那里进行反射)-或与泛型混合(没有真正的原因):

var attrs = Attribute.Read<Person>("FirstName");

【讨论】:

  • @Segfault 我的警告仍然适用:我个人不会让该代码任何靠近对象构造函数 - 它是错误的地方。
  • 是的,我只是想展示我正在尝试做的事情,同时使代码尽可能清晰
  • 如何检查是否需要特定属性?我正在创建一个类的实例为object obj = Activator.CreateInstance("myModel"),我需要检查是否需要特定属性:obj.GetType().GetProperty("prop1").......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-06
  • 1970-01-01
  • 2014-10-24
  • 2011-01-20
相关资源
最近更新 更多