如果我正确理解你的问题,这可以通过反射的一点帮助来完成......
首先添加一个:using System.Reflection;
到你的cs文件的顶部。
由于我不知道您使用的是 WPF 还是 Winforms - 这里有 2 个示例...
WPF:
您可以使用此版本的 SetParam:
private void SetParam(string name, string property, dynamic value)
{
// Find the object based on it's name
object target = this.FindName(name);
if (target != null)
{
// Find the correct property
Type type = target.GetType();
PropertyInfo prop = type.GetProperty(property);
// Change the value of the property
prop.SetValue(target, value);
}
}
用法:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
SetParam("textbox", "Text", "Hello");
textbox
像这样声明的地方:
<TextBox x:Name="textbox" />
对于 Winforms,只需将 SetParam 更改为:
private void SetParam(string name, string property, dynamic value)
{
// Find the object based on it's name
object target = this.Controls.Cast<Control>().FirstOrDefault(c => c.Name == name);
if (target != null)
{
// Find the correct property
Type type = target.GetType();
PropertyInfo prop = type.GetProperty(property);
// Change the value of the property
prop.SetValue(target, value);
}
}