c#编程
完成条件
数据分组方式
C# 提供多种方法将数据集合分组,例如枚举、结构和数组。
枚举 (Enumerations)
枚举是一种数据类型,用于枚举一组项目,为每个项目分配一个标识符(名称),同时为排序提供底层基类型。默认底层类型是 int
,但可以使用任何整型(除 char
之外)。
声明枚举
enum Weekday { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
上述枚举中的元素作为常量使用:
Weekday day = Weekday.Monday;
if (day == Weekday.Tuesday)
{
Console.WriteLine("Time sure flies by when you program in C#!");
}
分配显式值
如果不指定值,第一个元素默认为 0
,其余依次递增。可以显式分配值:
enum Age { Infant = 0, Teenager = 13, Adult = 18 };
Age myAge = Age.Teenager;
Console.WriteLine("You become a teenager at an age of {0}.", (int)myAge);
自定义底层类型
可以通过冒号指定非 int
类型的底层类型:
enum CardSuit : byte { Hearts, Diamonds, Spades, Clubs };
枚举的值可以通过调用 .ToString()
输出其名称:
Console.WriteLine(CardSuit.Hearts.ToString()); // 输出 "Hearts"
结构 (Structs)
结构 (struct
) 是轻量级对象,主要用作值类型变量集合的容器。与类类似,结构可以有构造函数、方法,并实现接口,但也有以下不同:
- 值类型:结构是值类型,类是引用类型。这使得结构作为参数传递时的行为不同。
- 不支持继承:结构不能继承其他结构或类。
- 默认构造函数:结构总是有默认构造函数,且不能被隐藏。
声明结构
struct Person
{
public string name;
public System.DateTime birthDate;
public int heightInCm;
public int weightInKg;
}
使用结构
Person dana = new Person();
dana.name = "Dana Developer";
dana.birthDate = new DateTime(1974, 7, 18);
dana.heightInCm = 178;
dana.weightInKg = 50;
if (dana.birthDate < DateTime.Now)
{
Console.WriteLine("Thank goodness! Dana Developer isn't from the future!");
}
带构造函数的结构
struct Person
{
string name;
DateTime birthDate;
int heightInCm;
int weightInKg;
public Person(string name, DateTime birthDate, int heightInCm, int weightInKg)
{
this.name = name;
this.birthDate = birthDate;
this.heightInCm = heightInCm;
this.weightInKg = weightInKg;
}
}
简化初始化语法
struct Person
{
public string Name;
public int Height;
public string Occupation;
}
Person john = new Person { Name = "John", Height = 182, Occupation = "Programmer" };
结构主要用于性能优化,适合小于或等于 16 字节的数据。如果不确定,建议使用类。
数组 (Arrays)
数组表示一组相同类型的项目,其长度在声明时固定,无法更改。
声明数组
用常量定义长度:
int[] integers = new int[20];
用变量定义长度:
int length;
Console.Write("How long should the array be? ");
length = int.Parse(Console.ReadLine());
double[] doubles = new double[length];
C# 提供多种方式根据具体需求选择数据分组方式:枚举适合逻辑相关的常量集合,结构适合轻量值类型容器,数组适合固定长度的同类型项目集合。
最后修改: 2025年01月11日 星期六 21:23