[英]Modifying Variable Names in C#
我不確定標題是否正確,因為我不確定如何解釋。 我遇到過許多情況,能夠動態修改變量名的一部分(例如帶后綴的整數)可以為我節省大量時間,並使我的代碼更整潔,但我不確定該怎么做。 這是我最近遇到的一個例子。
我在3 x 3的網格中有9個PictureBox。 每個PictureBox都有一個單元格名稱,其后是數字,因此為cell1,cell2,cell3等。我想獲取每個單元格的背景色,並將它們分配給變量,同時將它們轉換為字符串,如下所示:
for (int i = 1; i < 10; i++)
{
string ci = celli.BackColor.ToString();
}
有什么方法可以讓i變量僅將其數字值插入占位符,而不是在變量名后附加i? 我可以用某種支架包裝嗎? 我已經嘗試過使用Google進行搜索,但發現僅使用關鍵字很難搜索。
提前致謝。
您可能正在使用可視化表單編輯器,執行此操作的最佳方法可能是通過代碼(而不是可視化)生成網格。
另一個解決方案是使其成為矩陣:
PictureBox[,] cell = new PictureBox[,] {
{ cell1, cell2, cell3 },
{ cell4, cell5, cell6 },
{ cell7, cell8, cell9 }
};
string[,] c = new string[3, 3];
for(int y=0; y<3; y++)
for(int x=0; x<3; x++)
c[x, y] = cell[x, y].BackColor.ToString();
祝您的代碼好運。
您想生成所有圖片框的列表或集合,以便可以通過指定它們的索引來訪問它們。 一種方法是在運行時生成PictureBoxes:
像這樣:
List<PictureBox> myPics = new List<PictureBox>();
int picWidth = 100;
int picHeight = 100;
for (x = 0; x <= this.Width; x += picWidth) {
for (y = 0; y <= this.Height; y += picHeight) {
PictureBox pic = new PictureBox();
pic.Image = pic.Image;
// Your image
pic.Location = new Point(x, y);
this.Controls.Add(pic);
myPics.Add(pic);
}
}
// Do something with myPics...
另一種方法是,當窗體上確實具有所有圖片框時,可以遍歷所有控件,檢查哪些是圖片框,然后檢查其Name屬性以標識其索引。 然后相應地對他們進行處理。
foreach (void ctrl_loopVariable in this.Controls) {
ctrl = ctrl_loopVariable;
if (ctrl.GetType() == typeof(PictureBox)) {
if (ctrl.Name == "your picture box name to test") {
// Do something here with ctrl
}
}
}
(以上代碼已從VB轉換為C#,請諒解轉換問題)
您的意圖是動態引用這些控件。
為了實現這一點,有兩種選擇:
第一點解釋了什雷亞斯·卡普爾的回答。 第二個可能是像這樣的圓錐體
readonly Dictionary<Point,PictureBox> _dynamicMappedBoxes =
new Dictionary<Point,PictureBox>();
// Call this once in the beginning ofr your program
void createDynamicMapping()
{
foreach(PictureBox box in Controls.OfType<PictureBox>())
{
Point coords = getCoordinatesFromName(box);
_dynamicMappedBoxes.Add(coords, box);
}
}
Point getCoordinatesFromName(PictrueBox box)
{
int x = int.Parse(box.Name.SubString(IdontKnow);
int y = int.Parse(box.Name.SubString(IdontKnow);
retrun new Point(x,y);
}
//usage
string colorName = dynamicMappedBoxes[new Point(x,y)].BackColor.ToString();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.