我可以使用 foreach 从集合中仅返回特定类型吗?
如果我输入下面的代码,则会出现错误。基本上,当 foreach 遇到不是标签的 Control 时,它就会中断。
foreach (Label currControl in this.Controls()) {
...
}
我必须做这样的事情。
foreach (Control currControl in this.Controls()) {
if(typeof(Label).Equals(currControl.GetType())){
...
}
}
任何人都可以想出一种更好的方法来做到这一点,而无需我检查类型吗?我可以以某种方式让 foreach 跳过不是标签的对象吗?
If I enter the code below, I get an error. Basically, the foreach will break when it comes across a Control that isn't a label.
foreach (Label currControl in this.Controls()) {
...
}
I have to do something like this.
foreach (Control currControl in this.Controls()) {
if(typeof(Label).Equals(currControl.GetType())){
...
}
}
can anyone think of a better way of doing it without me needing to check the type? Can I somehow get foreach to skip the objects that aren't Labels?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用的是 .NET 3.5 或更高版本,则可以执行类似这样的
操作
OfType
将忽略无法转换为 T 的类型。请参阅 http://msdn.microsoft.com/en-us/library/bb360913.aspxIf you're on .NET 3.5 or newer, you can do something like this
OfType<T>
will ignore types that cannot be cast to T. See http://msdn.microsoft.com/en-us/library/bb360913.aspxBrian 在
OfType
方面给出了最合适的答案。不过,我想指出的是,在您确实需要检查类型的情况下,有一种更好的方法。除了当前代码之外,您还可以使用:
或:
请注意,这两种替代方案都将包含
Label
的子类,而您的原始代码则不包含这些子类。Brian has given the most appropriate answer in terms of
OfType
. However, I wanted to point out that there's a better way of checking for types in cases where you do need to do it. Instead of your current code:You can use:
or:
Note that both of these alternatives will also include subclasses of
Label
, which your original code doesn't.