如何使用 Foreach 语句对我的文本框执行某些操作?
foreach (Control X in this.Controls)
{
Check if the controls is a TextBox, if it is delete it's .Text letters.
}
最佳答案
如果您使用的是 C# 3.0 或更高版本,您可以执行以下操作
foreach ( TextBox tb in this.Controls.OfType<TextBox>()) {
..
}
如果没有 C# 3.0,您可以执行以下操作
foreach ( Control c in this.Controls ) {
TextBox tb = c as TextBox;
if ( null != tb ) {
...
}
}
或者更好的是,在 C# 2.0 中编写 OfType。
public static IEnumerable<T> OfType<T>(IEnumerable e) where T : class {
foreach ( object cur in e ) {
T val = cur as T;
if ( val != null ) {
yield return val;
}
}
}
foreach ( TextBox tb in OfType<TextBox>(this.Controls)) {
..
}
关于c# - Foreach 控件在窗体中,我怎样才能对我的窗体中的所有文本框做些什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1499049/