关于C#枚举(摘)
1.11 枚举(Enums)
枚举声明为一组属性相同的常量定义一个统一的类别名字。它常用于一些在编译时已知范围的常量。但这些常量的具体值要在执行时才能确定。比如,已知三原色是红蓝绿,它们同属于颜色。可以定义如下:
*/
enum Color {
Red,
Blue,
Green
}
/*
我们创建一个shape(形体)类,每一个形体都会有颜色。颜色是属于“shape”的属性。但具体的颜色就要在执行时才能决定:
*/
class Shape
{
public void Fill(Color color) {
switch(color) {
case Color.Red:
...
break;
case Color.Blue:
...
break;
case Color.Green:
...
break;
default:
break;
}
}
}
/*
这个File方法地说明了如何将一种给定的颜色赋予shape类。枚举比起普通整数常量的优胜之处在于:它使得代码更容易阅读理解和更安全。枚举的常量可以由编译器决定。使用时编译器还可以检查它的有效性。枚举其实不是c#特有的
注意 此示例显示如何使用 ToString 的一个重载版本。有关其他可用示例,请参阅单独的重载主题。
[C#]
// Sample for Enum.ToString(String)
using System;
class Sample
{
enum Colors {Red, Green, Blue, Yellow};
public static void Main()
{
Colors myColor = Colors.Yellow;
Console.WriteLine("Colors.Red = {0}", Colors.Red.ToString("d"));
Console.WriteLine("Colors.Green = {0}", Colors.Green.ToString("d"));
Console.WriteLine("Colors.Blue = {0}", Colors.Blue.ToString("d"));
Console.WriteLine("Colors.Yellow = {0}", Colors.Yellow.ToString("d"));
Console.WriteLine("{0}myColor = Colors.Yellow{0}", Environment.NewLine);
Console.WriteLine("myColor.ToString(\"g\") = {0}", myColor.ToString("g"));
Console.WriteLine("myColor.ToString(\"G\") = {0}", myColor.ToString("G"));
Console.WriteLine("myColor.ToString(\"x\") = {0}", myColor.ToString("x"));
Console.WriteLine("myColor.ToString(\"X\") = {0}", myColor.ToString("X"));
Console.WriteLine("myColor.ToString(\"d\") = {0}", myColor.ToString("d"));
Console.WriteLine("myColor.ToString(\"D\") = {0}", myColor.ToString("D"));
Console.WriteLine("myColor.ToString(\"f\") = {0}", myColor.ToString("f"));
Console.WriteLine("myColor.ToString(\"F\") = {0}", myColor.ToString("F"));
}
}
/*
This example produces the following results:
Colors.Red = 0
Colors.Green = 1
Colors.Blue = 2
Colors.Yellow = 3
myColor = Colors.Yellow
myColor.ToString("g") = Yellow
myColor.ToString("G") = Yellow
myColor.ToString("x") = 00000003
myColor.ToString("X") = 00000003
myColor.ToString("d") = 3
myColor.ToString("D") = 3
myColor.ToString("f") = Yellow
myColor.ToString("F") = Yellow
*/
Enum.ToString 方法 ()
返回值
此实例的值的字符串表示。
备注
使用此方法就如同指定了通用格式字符“G”一样。也就是说,如果未将 FlagsAttribute 应用到此枚举类型,且存在与此实例的值相等的已命名常数,则返回值为包含该常数名称的字符串。如果应用了 FlagsAttribute,且存在与此实例的值相等的一个或多个已命名常数的组合,则返回值是一个字符串,该字符串包含用分隔符分隔的常数名称列表。其他情况下,返回值是此实例的数值的字符串表示形式。
有关格式字符的更多信息,请参见 Format 方法的备注部分。有关一般格式化的更多信息,请参见格式化概述。
.NET Framework 精简版 - Windows CE .NET 平台说明: 因为此方法搜索元数据表,所以它大量占用系统资源,从而可能影响性能。
示例
[C#]
using System;
public class EnumSample {
enum Colors {Red = 1, Blue = 2};
public static void Main() {
Enum myColors = Colors.Red;
Console.WriteLine("The value of this instance is '{0}'",
myColors.ToString());
}
}
/*
Output.
The value of this instance is 'Red'.
*/