我想在加载表单时更改分配给 c# (visual studio 2010) 中表单控件的值。我希望我的表单应该显示给最终用户,但在我从服务器获取数据的同时,我希望它能够将相同的数据反映到控件上。(不使用任何计时器、线程或任何事件)。
示例: textBox1.text ="abc";
如果服务器发送“xyz”而不是表单已经加载,testbox 的值应该自动更改为 xyz。
没有任何点击或任何类型的事件。
我想在加载表单时更改分配给 c# (visual studio 2010) 中表单控件的值。我希望我的表单应该显示给最终用户,但在我从服务器获取数据的同时,我希望它能够将相同的数据反映到控件上。(不使用任何计时器、线程或任何事件)。
示例: textBox1.text ="abc";
如果服务器发送“xyz”而不是表单已经加载,testbox 的值应该自动更改为 xyz。
没有任何点击或任何类型的事件。
您必须查看 c# 中的 Properties 是如何工作的:
如果我们在sharplab.io 上反编译一个简单的类
public class C {
public int foo
{get;set;}
}
您将看到编译将始终生成支持字段以及 getter 和 setter 方法。
因此,如果您不想触发事件,则必须绕过这些方法,因为事件很可能会在那里触发。
这应该可以通过通常很容易做到的反射来实现。但是文本框似乎没有一个支持字段,它的文本属性很容易访问。很可能它是由其私有 StringSource 字段设置的。它来自内部类型 StringSource。所以首先我们必须得到类型。获取对构造函数的引用,然后调用它并设置私有字段。
这就是我已经走了多远:
private int number = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
number++;
this.textBox1.Text = number.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
number++;
Type cTorType = typeof(string[]);
string[] cTorParams = new string[] { number.ToString() };
Type type = this.textBox1.GetType().GetRuntimeFields().ElementAt(11).FieldType;
ConstructorInfo ctor = type.GetConstructor(new[] { cTorType });
object stringSourceInstance = ctor.Invoke(new[] { cTorParams });
this.textBox1.GetType().GetRuntimeFields().ElementAt(11).SetValue(this.textBox1, stringSourceInstance);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
MessageBox.Show("Changed!");
}
我建议深入研究反射,并通过使用 typeof(TextBox).GetFields / .GetProperties 查看您可以在 TextBox 类中找到什么,因为某处必须有一个字段或属性,您可以更改它以绕过您的 setter 方法触发事件。
希望这可以帮助。