繁体   English   中英

以下 VB.NET 代码的 C# 等效项是什么?

[英]What's the C# equivalent of the following VB.NET code?

我有这段用 VB.NET 编写的代码,我需要将其转换为 C#,但我遇到了一些问题。

这是VB中的代码:

For Each c in Me.Controls
    If TypeOf (c) Is PictureBox Then
        CType(c,PictureBox).Image = icon;
        AddHandler c.Click, AddressOf PictureBox10_Click
    End If

所以基本上我试图让它检查PictureBoxes并给它们一个图标并使这些PictureBoxes具有与PictureBox10 Click事件相同的功能。

这是我用 C# 编写的代码:

foreach (Control c in this.Controls)
{
    if (c.GetType() == typeof(System.Windows.Forms.PictureBox))
    {
        ((PictureBox)c).Image = Properties.Resorces.available;
        c.Click += new System.EventHandler(this.pictureBox10_Click);
    }
}

它一直工作到图像部分,但我无法让EventHandler工作。

这也是 PictureBox10 单击事件的作用:

private void pictureBox10_Click(object sender, EventArgs e) 
{
    if (pictureBox10.Image == Properties.Resorces.available)
        pictureBox10.Image = Properties.Resorces.selected;
    else if (pictureBox10.Image == Properties.Resorces.selected)
        pictureBox10.Image = Properties.Resorces.available;
}

很感谢任何形式的帮助。

以选择一个PictureBox的代码可以使用被简化System.Linq扩展方法, OfType ,它选择在指定唯一的控件OfType参数,并返回它们作为该类型。 此外,我们可以为所有这些控件分配一个公共事件处理程序:

foreach (PictureBox pb in Controls.OfType<PictureBox>())
{
    pb.Image = Properties.Resorces.available;
    pb.Click += PictureBox_Click;  // Defined below
}

然后在事件处理程序中,我们将sender PictureBox转换为PictureBox这样我们就有了一个强类型对象,这允许我们设置Image属性:

private void PictureBox_Click(object sender, EventArgs e)
{
    var thisPictureBox = sender as PictureBox;

    // May not be necessary, but it's a good practice to ensure that 'sender' was actually
    // a PictureBox and not some other object by checking if 'thisPictureBox' is 'null'
    if (thisPictureBox == null) return;

    if (thisPictureBox.Image == Properties.Resorces.available)
    {
        thisPictureBox.Image = Properties.Resorces.selected;
    {
    else if (thisPictureBox.Image == Properties.Resorces.selected)
    {
        thisPictureBox.Image = Properties.Resorces.available;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM