C# 在何处使用枚举以及如何模拟messageboxICon枚举
我想知道为什么以及在哪里使用枚举数,我有一组图像,我想给每个图像分配数字,并将其放入枚举中,我想设置数字,而不是 当我想设置图像时,使用整个文件名,就像MessageBoxIcon枚举一样 谢谢。只要有一组值可供选择,就可以使用枚举。枚举的另一个常用用法是设置 对于您的问题,我认为枚举可能不是最好的方法,因为I文件名可能包含c#code中不允许的字符。尽管您可以使用。只需在参数中添加C# 在何处使用枚举以及如何模拟messageboxICon枚举,c#,.net,enums,C#,.net,Enums,我想知道为什么以及在哪里使用枚举数,我有一组图像,我想给每个图像分配数字,并将其放入枚举中,我想设置数字,而不是 当我想设置图像时,使用整个文件名,就像MessageBoxIcon枚举一样 谢谢。只要有一组值可供选择,就可以使用枚举。枚举的另一个常用用法是设置 对于您的问题,我认为枚举可能不是最好的方法,因为I文件名可能包含c#code中不允许的字符。尽管您可以使用。只需在参数中添加this关键字,使GetDescription方法成为一个函数。我猜您指的是枚举数,而不是枚举数。枚举用于指定可能
this
关键字,使GetDescription方法成为一个函数。我猜您指的是枚举数,而不是枚举数。枚举用于指定可能的符号值或含义的离散集合。你确定这就是你想要的吗?请注意,枚举是在编译时嵌入的,以后不能更改,因此,如果您的映像集在运行时要更改,则需要其他一些数据结构
还要注意的是,枚举不能包含成员名称以外的任何信息,因此,例如,您将无法将文件名与其关联。要执行此操作,您需要一个或类似的文件,例如:
enum Image
{
Image1,
Image2,
Image3
}
在某些方法中的一个例子:
var imageFileNames = new Dictionary<Image, string>();
imageFileNames[Image.Image1] = "/path/to/file1.jpg";
imageFileNames[Image.Image2] = "/path/to/file2.jpg";
imageFileNames[Image.Image3] = "/path/to/file3.jpg";
var-imageFileNames=newdictionary();
imageFileNames[Image.Image1]=“/path/to/file1.jpg”;
imageFileNames[Image.Image2]=“/path/to/file2.jpg”;
imageFileNames[Image.Image3]=“/path/to/file3.jpg”;
我强烈建议您将希望能够从中选择的图像存储在C#项目的资源文件中。(有关如何执行此操作,请参见。)
然后,您需要在代码中创建一个枚举(它只是一个定义集合中所有可能值的列表)。我建议在项目中创建一个新的空文件来保存枚举,并将其命名为与枚举相同的名称,以便可以轻松地再次找到它。您的枚举文件将如下所示(您可以添加任意数量的值):
然后,无论您希望在何处指定要显示的图像,都可以引用其中一个枚举值。在要处理显示图像的代码中,必须使用switch
语句将指定的枚举值转换为存储在项目资源中的图像文件:
private void FlowerButtonClick()
{
//When this button is clicked, change the displayed image to a flower picture
UpdateDisplayedImage(PartyImage.Flower);
}
//etc.
public void UpdateDisplayedImage(PartyImage image)
{
//Determine the image that was specified in the parameter,
//and update my picture box accordingly
switch (PartyImage)
{
case None:
myPicBox.Image = null;
break;
case Smileyface:
myPicBox.Image = MyWindowsApp.Properties.Resources.SmileyFace;
break;
case Flower:
myPicBox.Image = MyWindowsApp.Properties.Resources.Flower;
break;
case Balloon:
myPicBox.Image = MyWindowsApp.Properties.Resources.Balloon;
break;
}
}
在上面的示例中,FlowerButtonClick
方法只是指定希望显示PartyImage
枚举中名为Flower
的图像。它包含的代码相当于调用MessageBox.Show
函数并指定要显示在消息框上的图像。您可以拥有任意数量的这些方法,它们可以位于代码中的任何位置,就像您可以在任何位置显示带有指定图标的消息框一样
updatedisplaydimage
方法执行实际工作,从项目的资源文件中检索与指定的枚举值对应的图像并显示它。这相当于MessageBox.Show
函数在创建并显示带有指定图标的新消息框时在内部完成的工作
有关枚举的详细信息,请参阅推荐阅读:
private void FlowerButtonClick()
{
//When this button is clicked, change the displayed image to a flower picture
UpdateDisplayedImage(PartyImage.Flower);
}
//etc.
public void UpdateDisplayedImage(PartyImage image)
{
//Determine the image that was specified in the parameter,
//and update my picture box accordingly
switch (PartyImage)
{
case None:
myPicBox.Image = null;
break;
case Smileyface:
myPicBox.Image = MyWindowsApp.Properties.Resources.SmileyFace;
break;
case Flower:
myPicBox.Image = MyWindowsApp.Properties.Resources.Flower;
break;
case Balloon:
myPicBox.Image = MyWindowsApp.Properties.Resources.Balloon;
break;
}
}