Dis*_*ive 5 c# collections foreach
如果我输入下面的代码,我会收到错误.基本上,当遇到不是标签的Control时,foreach会断开.
foreach (Label currControl in this.Controls()) {
...
}
Run Code Online (Sandbox Code Playgroud)
我必须做这样的事情.
foreach (Control currControl in this.Controls()) {
if(typeof(Label).Equals(currControl.GetType())){
...
}
}
Run Code Online (Sandbox Code Playgroud)
没有我需要检查类型,谁能想到更好的方法呢?我可以以某种方式获得foreach跳过不是标签的对象吗?
Bri*_*sen 10
如果您使用的是.NET 3.5或更高版本,则可以执行此类操作
foreach(var label in this.Controls().OfType<Label>()) {
}
Run Code Online (Sandbox Code Playgroud)
OfType<T>将忽略无法转换为T的类型.请参阅http://msdn.microsoft.com/en-us/library/bb360913.aspx
Brian给出了最恰当的答案OfType.不过,我想指出的是,有检查的情况下类型,你一个更好的方式做需要做的.而不是您当前的代码:
if(typeof(Label).Equals(currControl.GetType())){
...
}
Run Code Online (Sandbox Code Playgroud)
您可以使用:
if (currControl is Label)
{
Label label = (Label) currControl;
// ...
}
Run Code Online (Sandbox Code Playgroud)
要么:
Label label = currControl as Label;
if (label != null)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
请注意,这两个方案都将还包括的子类Label,你的原代码没有.
| 归档时间: |
|
| 查看次数: |
2273 次 |
| 最近记录: |