基本类型--枚举类型和位标志
12.1枚举类型
internal sealed class AboutEnum
{
static void Main(string[] args)
{
Console.WriteLine("---GetUnderlyingType方法---");
Console.WriteLine(Enum.GetUnderlyingType(typeof(EColor)));
EColor c1 = new EColor();
c1 = EColor.Red;
Console.WriteLine("---ToString方法---");
Console.WriteLine(c1.ToString());
Console.WriteLine("---GetValues方法---");
EColor[] colors = (EColor[])Enum.GetValues(typeof(EColor));
foreach (EColor cc in colors)
{
Console.WriteLine(cc);
}
Console.WriteLine("---GetValues方法---");
Console.WriteLine(Enum.GetName(typeof(EColor),2));
Console.WriteLine("---GetNames方法---");
String[] str = (String[])Enum.GetNames(typeof(EColor));
foreach (string s in str)
{
Console.WriteLine(s);
}
Console.WriteLine("---Parse方法---");
EColor c2 = (EColor)Enum.Parse(typeof(EColor), "1", true);
Console.WriteLine(c2);
Console.WriteLine("---IsDefined方法---");
SetColor((EColor)1);
// SetColor((EColor)10); //引用异常
Console.ReadLine();
}
public static void SetColor(EColor c)
{
if (!Enum.IsDefined(typeof(EColor), c))
{
throw (new ArgumentOutOfRangeException("c", c, "不合法的Color value"));
}
else
Console.WriteLine(Enum.GetName(typeof(EColor), c));
}
}
//EColor和调用它的类型AboutEnum处于同级
public enum EColor {
Write,
Red,
Blue,
Yello
}
12.2位标志{
static void Main(string[] args)
{
Console.WriteLine("---GetUnderlyingType方法---");
Console.WriteLine(Enum.GetUnderlyingType(typeof(EColor)));
EColor c1 = new EColor();
c1 = EColor.Red;
Console.WriteLine("---ToString方法---");
Console.WriteLine(c1.ToString());
Console.WriteLine("---GetValues方法---");
EColor[] colors = (EColor[])Enum.GetValues(typeof(EColor));
foreach (EColor cc in colors)
{
Console.WriteLine(cc);
}
Console.WriteLine("---GetValues方法---");
Console.WriteLine(Enum.GetName(typeof(EColor),2));
Console.WriteLine("---GetNames方法---");
String[] str = (String[])Enum.GetNames(typeof(EColor));
foreach (string s in str)
{
Console.WriteLine(s);
}
Console.WriteLine("---Parse方法---");
EColor c2 = (EColor)Enum.Parse(typeof(EColor), "1", true);
Console.WriteLine(c2);
Console.WriteLine("---IsDefined方法---");
SetColor((EColor)1);
// SetColor((EColor)10); //引用异常
Console.ReadLine();
}
public static void SetColor(EColor c)
{
if (!Enum.IsDefined(typeof(EColor), c))
{
throw (new ArgumentOutOfRangeException("c", c, "不合法的Color value"));
}
else
Console.WriteLine(Enum.GetName(typeof(EColor), c));
}
}
//EColor和调用它的类型AboutEnum处于同级
public enum EColor {
Write,
Red,
Blue,
Yello
}
作者:青羽