简体   繁体   English

通过计算引用C#对象

[英]Referencing a C# object by calculation

I have 8 picture boxes, named p1 through p8. 我有8个图片框,分别命名为p1到p8。

I would like to change the backcolor of one of those picture boxes, depending on the result of a calculation. 我想根据计算结果更改其中一个图片框的背景色。

I can create a string beginning with the letter 'p' and affix the calculated number to that string. 我可以创建一个以字母“ p”开头的字符串,并将计算得出的数字附加到该字符串上。

I am looking for a clever way to reference a picture box with this string (eg. "p4"). 我正在寻找一种聪明的方法来引用带有此字符串的图片框(例如“ p4”)。 My question is, is this possible? 我的问题是,这可能吗?

If you really want to refer to them by a string like p4 then put them in a dictionary 如果您真的想通过p4类的字符串来引用它们,则将它们放入字典中

var dict = new Dictionary<string,PictureBox>();
dict.add("p1",myP1dict);
dict.add("p2",myP2dict);
// etc
dict["p2"].BackgroundColor = newColor;

More likely, you could just put them in an array 您更有可能将它们放在一个数组中

var arr = new PictureBox[8]
arr[0] = myPictBox1
arr[1] = myPictBox2
//etc
arr[1].BackgroundColor = newColor;

And refer to them by index. 并按索引引用它们。

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

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