Find a private field with Reflection?

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

    You can do it just like with a property:

    FieldInfo fi = typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance);
    if (fi.GetCustomAttributes(typeof(SomeAttribute)) != null)
        ...
    

提交回复
热议问题