Copying variables from one picturebox to another without making them change with each other

岁酱吖の 提交于 2019-12-25 13:46:09

问题


I would like to copy a picturebox to another picturebox, but I do not want them to change with each other.

PictureBox picbox1 = new PictureBox();
PictureBox picbox2 = picbox1;

picbox1.Visible = false; //The problem here is that picbox2.Visible will also become false

I would like to make picbox1 change without changing picbox2....

How would I be able to do that?


回答1:


Probably the best way to maintain clean code is to create an extension method, also note that your second picturebox is currently not added to controls.

public static class MyExtensions
{
    public static PictureBox CreateNewWithAttributes(this PictureBox pb)
    {
        return new PictureBox { Image = pb.Image, Width = pb.Width };
    }
}

Picturebox p2 = p1.CreateNewWithAttributes();
this.Controls.Add(p2);

More can be read on extension methods here




回答2:


use this...

PictureBox p1 = new PictureBox();
PictureBox p2 = new PictureBox();
Bitmap b = new Bitmap(p1.Image);
p2.Image = b;
p1.Visible = false;


来源:https://stackoverflow.com/questions/23153434/copying-variables-from-one-picturebox-to-another-without-making-them-change-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!