Find a private field with Reflection?

前端 未结 10 1188
自闭症患者
自闭症患者 2020-11-22 16:17

Given this class

class Foo
{
    // Want to find _bar with reflection
    [SomeAttribute]
    private string _bar;

    public string BigBar
    {
        ge         


        
相关标签:
10条回答
  • 2020-11-22 16:54

    I came across this while searching for this on google so I realise I'm bumping an old post. However the GetCustomAttributes requires two params.

    typeof(Foo).GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
    .Where(x => x.GetCustomAttributes(typeof(SomeAttribute), false).Length > 0);
    

    The second parameter specifies whether or not you wish to search the inheritance hierarchy

    0 讨论(0)
  • 2020-11-22 16:58

    I use this method personally

    if (typeof(Foo).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Any(c => c.GetCustomAttributes(typeof(SomeAttribute), false).Any()))
    { 
        // do stuff
    }
    
    0 讨论(0)
  • 2020-11-22 16:59

    Yes, however you will need to set your Binding flags to search for private fields (if your looking for the member outside of the class instance).

    The binding flag you will need is: System.Reflection.BindingFlags.NonPublic

    0 讨论(0)
  • 2020-11-22 17:01

    Use BindingFlags.NonPublic and BindingFlags.Instance flags

    FieldInfo[] fields = myType.GetFields(
                             BindingFlags.NonPublic | 
                             BindingFlags.Instance);
    
    0 讨论(0)
提交回复
热议问题