版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ZFSR05255134/article/details/46916885
本次练习在Unity工程中实现。
C#遍历枚举的方法如下:
枚举可用来存储字符串与数字的值对,相当于一个对照表
常用方法:GetName(),GetValue(),Parse()
头文件:using System;
/// <summary>
/// 枚举星期
/// </summary>
public enum Weekdays { Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday };
/// <summary>
/// 遍历枚举
//// 访法一
/// </summary>
private void ergodicEnum1()
{
Debug.Log("-------------------------------------------------------------------");
foreach (int myday in Enum.GetValues(typeof(Weekdays)))
{
/// 枚举名字
string name = Enum.GetName(typeof(Weekdays), myday);
/// 枚举的值
int value = myday;
Debug.Log(string.Format("名字 = {0},值 = {1}", name, myday));
}
Debug.Log("-------------------------------------------------------------------");
}
/// <summary>
/// 枚举颜色
/// </summary>
public enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };
/// <summary>
/// 遍历枚举
//// 访法二
/// </summary>
private void ergodicEnum2()
{
Type color = typeof(Colors);
Debug.Log("-------------------------------------------------------------------");
foreach (string c in Enum.GetNames(color))
{
Debug.Log(string.Format("{0,-11}= {1}",c, Enum.Format(color, Enum.Parse(color, c), "d")));
}
Debug.Log("-------------------------------------------------------------------");
foreach (string c in Enum.GetNames(typeof(Colors)))
{
Debug.Log(string.Format("{0,-11}= {1}", c, Enum.Format(color, Enum.Parse(color, c), "d")));
}
Debug.Log("-------------------------------------------------------------------");
Colors myColors = Colors.Red | Colors.Green | Colors.Blue | Colors.Yellow;
Debug.Log(string.Format("myColors holds a combination of colors. Namely: {0}", myColors));
Debug.Log("-------------------------------------------------------------------");
}