您的代码的问题是它T
可以是任何类型,但并非所有类型都具有该属性ReadOnly
。因此编译器会窒息。
您不需要使用泛型来执行此操作:
private void SetReadOnly(Control parent, bool readOnly)
{
// Get all TextBoxes and set the value of the ReadOnly property.
foreach (var tb in parent.Controls.OfType<TextBox>())
tb.ReadOnly = readOnly;
// Recurse through all Controls
foreach(Control c in parent.Controls)
SetReadOnly(c, readOnly);
}
但是,如果您想使用泛型,可以这样做:
private void SetReadOnly<T>(Control parent, bool readOnly) where T : TextBox
{
// Get all TextBoxes and set the value of the ReadOnly property.
foreach (var tb in parent.Controls.OfType<T>())
tb.ReadOnly = readOnly;
// Recurse through all Controls
foreach(Control c in parent.Controls)
SetReadOnly<T>(c, readOnly);
}
这将限制泛型类型TextBox
或任何从它派生的类。这确保了该ReadOnly
属性将始终存在并且编译器知道这一点。