使用反射检查字段属性

时间:2016-02-23 17:59:20

标签: c# .net reflection

我试图在类中找到一个具有Obsolete属性的字段,

我所做的是,但是甚至认为该类型具有在迭代期间未找到的obselete属性:

public bool Check(Type type)
{
    FieldInfo[] fields = type.GetFields(BindingFlags.NonPublic |  BindingFlags.Instance);

  foreach (var field in fields)
  { 
     if (field.GetCustomAttribute(typeof(ObsoleteAttribute), false) != null)
     {
        return true
     }
  }
}

编辑:

class MyWorkflow: : WorkflowActivity
{
 [Obsolete("obselset")]
 public string ConnectionString { get; set; }
}

并像这样使用Check(typeof(MyWorkflow))

1 个答案:

答案 0 :(得分:3)

问题是ConnectionString既不是Field也不是NonPublic

您应该更正BindingFlags并使用GetProperties方法搜索属性。

尝试以下

public static bool Check(Type type)
{
  var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
  return props.Any(p => p.GetCustomAttribute(typeof(ObsoleteAttribute), false) != null);
}