C# 使用反射C调用私有字段中的公共函数#

C# 使用反射C调用私有字段中的公共函数#,c#,winforms,reflection,C#,Winforms,Reflection,我需要进入私人领域的公共功能 范例 public partial class Form1 : Form { MainControl mainControl = new MainControl(); public Form1() { InitializeComponent(); var frame = mainControl.GetType().GetField("CustomControl", System.Reflection.Bind

我需要进入私人领域的公共功能

范例

 public partial class Form1 : Form
{
    MainControl mainControl = new MainControl();
    public Form1()
    {
        InitializeComponent();
        var frame = mainControl.GetType().GetField("CustomControl", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        frame.GetType().GetMethod("Display").Invoke(mainControl, new object[] { });
    }
}

public class MainControl
{
    public MainControl()
    {
        CustomControl = new CustomControl();
    }

    CustomControl CustomControl;
}

public class CustomControl
{
    public CustomControl()
    {

    }

    public void Display()
    {
        MessageBox.Show("Displayed");
    }
}
这里我需要调用CustomControl类中的Display函数


但我对上述方法有异议。有人能帮我吗?

你似乎不太了解反思。要调用
Display
,您需要执行以下步骤:

  • CustomControl
    字段作为
    FieldInfo
  • 使用实例
    mainControl
  • 获取
    CustomControl
  • CustomControl
  • 使用
    CustomControl
您只执行了第一步,然后继续获取刚获取的字段类型,即
typeof(FieldInfo)
,然后尝试从
FieldInfo
获取
显示
FieldInfo
没有这样的方法

我方便地编写了这段代码,使每一行都对应于上面的一个步骤

var fieldInfo = mainControl.GetType().GetField("CustomControl", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var valueOfField = fieldInfo.GetValue(mainControl);
var customControlType = fieldInfo.FieldType;
var methodInfo = customControlType.GetMethod("Display");
methodInfo.Invoke(valueOfField, new object[] {});

例外情况是什么?您知道在设计时通过将
Modifiers
属性设置为
public
可以公开控件吗?如果您更改
var customControlType=typeof(CustomControl)
var customControlType=fieldInfo.FieldType,它将更一般