【问题标题】:C#: Is there a way to access a private getter and setter? [duplicate]C#:有没有办法访问私有的 getter 和 setter? [复制]
【发布时间】:2016-11-07 16:39:20
【问题描述】:

我是 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();

}

但它不会起作用。

谁能帮帮我?

【问题讨论】:

标签: c# oop private


【解决方案1】:
PropertyInfo property = typeof(Foo).GetProperty("Bar", BindingFlags.Instance | BindingFlags.NonPublic);
MethodInfo getMethod = property.GetGetMethod(true);
MethodInfo setMethod = property.GetSetMethod(true);

【讨论】:

  • 谢谢!我正在寻找这个答案! @Yarik
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-27
  • 1970-01-01
  • 2018-08-06
相关资源
最近更新 更多