使用反射设置 属性 个控件
Set property of control using reflection
如何 get/set 属性 of Control
(在本例中 Button
)?
我这样试过:
Type t = Type.GetType("System.Windows.Forms.Button");
PropertyInfo prop = t.GetType().GetProperty("Enabled");
if (null != prop && prop.CanWrite && prop.Name.Equals("button1"))
{
prop.SetValue(t, "False", null);
}
但 t 为空。这里有什么问题?
首先,你需要实例来设置属性,它是button1
:
object instance = button1;
您可能想找到它,例如让我们扫描 MyForm
类型的所有打开形式,并使用 "button1"
Name
:
查找 Button
using System.Linq;
...
object instance = Application
.OpenForms
.OfType<MyForm>()
.SelectMany(form => form.Controls.Find("button1", true))
.OfType<Button>()
.FirstOrDefault();
...
然后我们准备反射:
var prop = instance.GetType().GetProperty("Enabled");
if (prop != null && prop.CanWrite && prop.PropertyType == typeof(bool))
// we set false (bool, not string "False") value
// for instance button1
prop.SetValue(instance, false, null);
编辑:如果你想通过Type.GetType(...)
从string
获得Type
,你需要程序集限定名:
string name = typeof(Button).AssemblyQualifiedName;
你会得到类似
的东西
System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
演示:
Type t = Type.GetType(
@"System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
MessageBox.Show(t.Name);
如何 get/set 属性 of Control
(在本例中 Button
)?
我这样试过:
Type t = Type.GetType("System.Windows.Forms.Button");
PropertyInfo prop = t.GetType().GetProperty("Enabled");
if (null != prop && prop.CanWrite && prop.Name.Equals("button1"))
{
prop.SetValue(t, "False", null);
}
但 t 为空。这里有什么问题?
首先,你需要实例来设置属性,它是button1
:
object instance = button1;
您可能想找到它,例如让我们扫描 MyForm
类型的所有打开形式,并使用 "button1"
Name
:
Button
using System.Linq;
...
object instance = Application
.OpenForms
.OfType<MyForm>()
.SelectMany(form => form.Controls.Find("button1", true))
.OfType<Button>()
.FirstOrDefault();
...
然后我们准备反射:
var prop = instance.GetType().GetProperty("Enabled");
if (prop != null && prop.CanWrite && prop.PropertyType == typeof(bool))
// we set false (bool, not string "False") value
// for instance button1
prop.SetValue(instance, false, null);
编辑:如果你想通过Type.GetType(...)
从string
获得Type
,你需要程序集限定名:
string name = typeof(Button).AssemblyQualifiedName;
你会得到类似
的东西System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
演示:
Type t = Type.GetType(
@"System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
MessageBox.Show(t.Name);