.net中使用反射实例:操作非公有成员

来源:互联网 发布:知乎如何关闭问题 编辑:程序博客网 时间:2024/06/09 23:30

以下通过反射获取Form1中的私有字段textBox1,并设置其文本。

using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;


namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            setText();
        }




        public void setText()
        {
            Type type = GetType();
            FieldInfo fieldInfo = type.GetField("textBox1", BindingFlags.Instance | BindingFlags.NonPublic);
            TextBox textBox1 = (TextBox)fieldInfo.GetValue(this);
            textBox1.Text = "11111";

             
        }
    }
}
0 0
原创粉丝点击