简体   繁体   中英

Check fields attributes using reflection

I'm trying to find a fields in a class has a Obsolete attribute ,

What I have done is , but even thought the type has an obselete attribute its not found during iteration :

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
     }
  }
}

EDIT :

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

and using it like this , Check(typeof(MyWorkflow))

Problem is that ConnectionString is nor Field and nor NonPublic .

You should correct BindingFlags and also, use GetProperties method to search for properties.

Try the following

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM