如果我输入下面的代码,我会收到错误消息。基本上,foreach 在遇到不是标签的控件时会中断。
foreach (Label currControl in this.Controls()) {
...
}
我必须做这样的事情。
foreach (Control currControl in this.Controls()) {
if(typeof(Label).Equals(currControl.GetType())){
...
}
}
有谁能想出一种无需我检查类型的更好方法吗?我能否以某种方式让 foreach 跳过不是标签的对象?
最佳答案
如果您使用的是 .NET 3.5 或更新版本,则可以执行类似的操作
foreach(var label in this.Controls().OfType<Label>()) {
}
OfType<T>
将忽略无法转换为 T 的类型。参见 http://msdn.microsoft.com/en-us/library/bb360913.aspx
关于c# - 我可以使用 foreach 只返回集合中的特定类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2763501/