有什么方法可以使用 int 变量来完成组件名称吗?

Is there any way how i can use int variable to complete component name?

本文关键字:组件 方法 什么 可以使 变量 int      更新时间:2023-10-16

例如,我可以使用整数变量 x=5 来获取组件编号 5、图像 1、图像 2...图像5.

就像你在数组中使用变量来选择数组数组[x]的特定元素一样。

不是直接的,不是。 意思是,这样的事情是行不通的:

int x = 5;
Imagex->...

或:

int x = 5;
(Image + x)->...

正如其他答案所述,您可以将组件指针存储到数组中,然后根据需要使用该变量索引到该数组中,例如:

TImage* Images[5];
...
Images[0] = Image1;
Images[1] = Image2;
Images[2] = Image3;
Images[3] = Image4;
Images[4] = Image5;
...
int x = 5;
Images[x-1]->...

还有另一种选择 - 您可以使用组件所有者的FindComponent()方法(其中TForm是在设计时放置的任何组件的Owner(,例如:

int x = 5;
static_cast<TImage*>(Owner->FindComponent("Image"+String(x)))->...

然后,您可以通过在循环中使用FindComponent()来避免对引用进行硬编码,从而与数组方法结合使用:

TImage* Images[5];
...
for(int num = 1; i <= 5; ++num)
Images[num-1] = static_cast<TImage*>(Owner->FindComponent("Image"+String(num)));
...
int x = 5;
Images[x-1]->...

您可以使用向量保持,假设图像,然后仔细使用自定义函数按索引获取图像,您需要注意的技巧是,如果以某种方式对向量进行排序或任何元素更改其位置,那么您的代码将被破坏......

这里有一个例子..

#include <vector>
std::vector<abc::file> files {file1,file2,file3,file4};
abc::file getByIndex(int index)
{
if(index<0 || index>files.size())
return abc::file::invalid;
return files.at(index);
}
int main()
{
int i = 5; 
abc::file5 = getByIndex(i);
std::cout << 'here is the endn';
}
有什么

方法可以使用 int 变量来完成组件名称吗?

不。

但是,也没有必要,因为:

您可以使用数组中的变量来选择数组 Array[X] 的特定元素。

结论:您可以改用数组。