如何使用反射将控件转换为其类型以修改属性?

How to use reflection to cast a control as its type in order to modify properties?

这是我目前所做的一个例子:

book enable = false;
foreach (Control c in controlList)
{
    if (c is MyTextBox)
    {
        (c as MyTextBox).Enabled = enable;
    }
    if...
    ...
}

不是为每种类型的控件使用多个 if 语句,而是有没有一种方法可以获取控件的类型以便进行转换,然后能够访问和设置该控件的 属性?

这是使用反射的一个很好的例子。

Control class 包含一个 Enabled 属性,您可以使用它来更改 Control 的所有后代的启用状态。所以更改控件集合的启用状态的简单方法是:

bool enable = false;
foreach (Control c in controlList)
    c.Enabled = enable;

或者(既然你已经提到了 System.Web.UI 命名空间)你可以为你的 WebControl 派生对象做这个,假设 controlList 集合可以包含派生的东西来自 Control 但不一定来自 WebControl

foreach (WebControl c in controlList.OfType<WebControl>())
    c.Enabled = enable;

反射在某些情况下很方便,您可以用它做一些很酷的事情。有时这很冗长而且有点难以理解,但通常可以通过其他方式更简单地完成。

如果你有不同类型的任意对象的集合,其中一些可能有一个你可以设置的 bool Enabled 属性,但不能保证他们有一个共同的基础 class,您可以访问 Enabled 属性。然后你可以这样做:

bool enabled = false;
foreach (var obj in objectList)
{
    var tObj = obj.GetType();
    PropertyInfo piEnabled = tObj.GetProperty("Enabled", typeof(bool));
    if (piEnabled != null && piEnabled.CanWrite)
        piEnabled.SetValue(obj, enabled);
}

比通过 Control 父 [=40] 简单地访问 属性 更复杂,更不透明,而且 很多 慢=].