C#:有没有办法访问私有 getter 和 setter?

C#: Is there a way to access a private getter and setter?

我是 C# 的新手,我只是想知道是否有任何方法可以访问 getter 和 setter。

这是一个示例代码:

public class Foo
{
  private AnotherClass _here;
  private bool Bar
  {
    get{return _here.GetAnswer();}
    set(return _here.SetAnswer(value);)
  }
}

我知道 c# 中有反射功能,但据我所知,它只处理私有变量。

此外,我一直在尝试此代码:

public void func()
{

  MethodInfo privMethod = Foo.GetType().
                        GetMethod("Bar", BindingFlags.NonPublic | BindingFlags.Instance);

  object fff = privMethod.Invoke();

}

但是不行。

谁能帮帮我?

PropertyInfo property = typeof(Foo).GetProperty("Bar", BindingFlags.Instance | BindingFlags.NonPublic);
MethodInfo getMethod = property.GetGetMethod(true);
MethodInfo setMethod = property.GetSetMethod(true);