C# “更快的方法”;如果;声明
有没有更快的方法?我有36张不同的图片,当图片改变时,我有一个跟踪图像的字符串(旋转),image1是旋转=1,等等,我要做的是使用36 if语句,如下所示:C# “更快的方法”;如果;声明,c#,winforms,if-statement,C#,Winforms,If Statement,有没有更快的方法?我有36张不同的图片,当图片改变时,我有一个跟踪图像的字符串(旋转),image1是旋转=1,等等,我要做的是使用36 if语句,如下所示: if (rotation == 1) //This is picture1 { } else if (rotation == 2) //This is picture2 { } 一直到: else if (rotation == 36) //This is picture36 { } 有没有办法只需要一两行代码就知道它是什么样的
if (rotation == 1) //This is picture1
{
}
else if (rotation == 2) //This is picture2
{
}
一直到:
else if (rotation == 36) //This is picture36
{
}
有没有办法只需要一两行代码就知道它是什么样的旋转?
任何在你问之前说“检查”的人,我已经检查过了,我没有发现任何有用的东西,如果你发现了什么,请把它贴在这里
if语句的内部仅用于更改图像
谢谢。您可以使用一个包含所有图片类别的
数组,或者一个i字典
,或者一个开关
语句
例如,如果图片信息是字符串:
string[] pictures = {
"you might have a blank entry here if the first number is 1 instead of 0",
"picture1",
"picture2",
"picture3",
"picture4",
// ...and so on...
};
然后,查找图片是
if (picture >= 0 && picture < pictures.Length) { // The 0 might be 1 in your case
pictureInfo = pictures[picture];
}
switch语句
或者如果你有一个列表
——在这种情况下,T
是你可以做的图片
List<T> pictures = new List<T>();
T picture = pictures[rotation];
List pictures=new List();
T图片=图片[旋转];
最好的方法是使用int而不是字符串,然后可以使用开关大小写
Java7允许在switch语句中使用字符串,我不知道在C#中是否可以使用字符串。或者使用数组
picture = img[i];
或者实际使用索引命名图像(例如,image01.jpg
,image02.jpg
等)
数组给我的印象是最具可扩展性和简洁性的解决方案。这是一个长期的问题,我假设图像文件的名称将始终与旋转值相对应,如下所示
旋转=1----->filename=image1.png
旋转=2----->filename=image2.png
如果是这样,你可以这样做
string fileName = "image" + rotation + ".png";
您可以使用此选项选择或显示所需的文件。例如,如果打印旋转,请在文件中输入
if (rotation == 1) //This is picture1
{
System.out.println(1);
}
else if (rotation == 2) //This is picture2
{
System.out.println(2);
}
else if(rotation==36)
{
System.out.println(36);
}
您可以将整个代码更改为一行
System.out.println(rotation);
请显示一个if中的内容…创建一个数组并使用旋转
对其进行索引。正如拉斐尔所说,这完全取决于if块中的内容。如果你只是在为大卫的建议中的一幅图片建立索引,那么它是有效的。如果您正在创建HTML,那么您的图像文件名可以是myimage_{rotation}.jpg。在任何情况下,你都想使旋转成为某种索引。我的问题是,假设图像是image1,如果我按下图片框
右侧的按钮,它会显示image2,但如果我按下图片框
左侧的按钮,它会显示image36,因此,我不能像zam664所说的那样将我的图像命名为旋转。只需将图像存储在一个集合中,例如数组(image[]images
),并跟踪当前索引(i
)。单击按钮时,递增/递减i
,然后在PictureBox
@RaphaëlAlthaus中显示images[i]
,因为用户要求更快地执行if语句。我的答案是一种更快的方法,即使收益很低。不管怎样,我已经发布了做这件事的更好的选择。。。
string fileName = "image" + rotation + ".png";
if (rotation == 1) //This is picture1
{
System.out.println(1);
}
else if (rotation == 2) //This is picture2
{
System.out.println(2);
}
else if(rotation==36)
{
System.out.println(36);
}
System.out.println(rotation);