Find a private field with Reflection?

前端 未结 10 1404
自闭症患者
自闭症患者 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

提交回复
热议问题