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代码>,它将更一般