【发布时间】:2021-05-17 15:09:01
【问题描述】:
我在 VB.Net 中有这段代码:
Dim c As Control
For Each c In Me.Controls
If TypeOf (c) is PictureBox Then
CType(c, PictureBox).Image = My.Resources.available
End If
Next
什么是合适的 C# 代码?
【问题讨论】:
-
VB 代码一开始就不好。如果您使用
For Each pb In Me.Controls.OfType(Of PictureBox)(),那么您不需要If语句或额外的演员表。该代码直接转换为 C# 为foreach (var pb in this.Controls.OfType<PictureBox>)()。 -
@jmcilhinney 轻微错字更正:
foreach (var pb in this.Controls.OfType<PictureBox>())。 C# 也可能会删除this -
@CaiusJard,感谢您的更正。至于使用
this,我自己当然会放弃它,但它是原始VB中使用的Me的直接翻译,因此我选择包含它。