枚举-----变量类型,用户定义了一组可能的数值,这些数值可以用人类能理解的方式使用
结构-----合成的变量类型,由用户定义的一组其他变量类型组成
数组-----包含一种类型的多个变量,可以用下标访问各个数值
枚举不是仅仅声明一个给定类型的变量,而是声明和描述一个用户定义的类型,再声明这个新的类型的变量
枚举可以用enum关键字来定义
enum typeName
{
value1,
value2,
value3,
........
valueN
}
接着声明这个新类型的变量:
typeName varName;
并赋值:
varName=typeName.value;
枚举使用一个基本的类型来存储,枚举类型可以提取的每个值都存储为该基本类型的一个值,默认情况下,该类型为int.
在枚举声明中添加类型,就可以指定其他基本类型:
enum typeName : underlyingType
{
value1,//默认value1的值为0
value2,
value3,
...........
valueN
}//underlyingType可以是byte,sbyte,short,ushort,int,uint,long和ulong默认情况下,每个值都会根据定义的顺序(从0开始)
示例:
namespace ConsoleApplication4
{
enum orientation : byte
{
north=1, //逗号
south=2,
east=3,
west=4
}
class Program
{
static void Main(string[] args)
{
orientation myDirection = orientation.north;
Console.WriteLine("myDirection={0}",myDirection);
Console.ReadKey();
}
}
}//结果myDirection=north
将代码该为:
namespace ConsoleApplication4
{
enum orientation : byte
{
north=1,
south=2,
east=3,
west=4
}
class Program
{
static void Main(string[] args)
{
//orientation myDirection = orientation.north;
//Console.WriteLine("myDirection={0}",myDirection);
//Console.ReadKey();
byte directionByte;
string directionString;
orientation myDirection = orientation.north;
Console.WriteLine("myDirection={0}",myDirection);
directionByte = (byte)myDirection;
directionString = Convert.ToString(myDirection);//<=>myDirection.ToString();
Console.WriteLine("byte equivalent={0}",directionByte);
Console.WriteLine("string equivalent={0}",directionString);
Console.ReadKey();
}
}
}//结果为myDirection=north
byte equivalent=1
string equivalent=north
结构
namespace ConsoleApplication3
{
class Program
{
enum orientation : byte
{
north=1,
south=2,
east=3,
west=4
}
struct route
{
public orientation direction;
public double distance;
}
static void Main(string[] args)
{
route myRoute;
int myDirection = -1;
double myDistance;
Console.WriteLine("1) North/n2) South/n3) East/n4) West");
do
{
Console.WriteLine("Select a direction:");
myDirection=Convert.ToInt32(Console.ReadLine());
}while((myDirection<1)||(myDirection>4));
Console.WriteLine("Input a distance:");
myDistance = Convert.ToDouble(Console.ReadLine());
myRoute.direction = (orientation)myDirection;
myRoute.distance = myDistance;
Console.WriteLine("myRoute specifies a direction of{0} and a"+"distance of {1}",myRoute.direction,myRoute.distance);
Console.ReadKey();
}
}
}