/// <summary>
/// 第九章:使用枚举和结构创建值类型
/// </summary>
namespace Chapter9
{
class Program
{
///9.2.3声明结构变量
private Time currentTime;
static void Main(string[] args)
{
//9.1使用枚举
///9.1.2使用枚举
Season localVariable=Season.Fall;
Console.WriteLine(localVariable);
///9.1.3选择枚举字面值(给第一个变量赋值)
Console.WriteLine((int)localVariable);
///9.1.4选择枚举的基础类型
/*
* 枚举可基于8种整型的任何一种
*/
//9.2使用结构
///9.2.2理解结构和类的区别
/*
* 区别:
* 不能为结构声明默认构造器(无参构造器),因为会自动生成默认构造器(类不会)
* 类的实例字段可在声明时初始化,但结构不允许
* 结构是值类型(值),类是引用类型(对象)
* 结构存储在栈上,类存储在堆上
* 实例字段在结构声明时不能被初始化。在类声明时可以初始化。
*/
///9.2.4理解结构的初始化
Time now;//结构是值类型,不调用构造器也可以创建结构表变量,但是其中的字段并未初始化
///9.2.5复制结构变量
now = new Time(5, 6, 30);
Time copy = now;//赋值了才可以复制
Console.ReadLine();
}
/// <summary>
/// 9.1.1声明枚举
/// </summary>
enum Season
{
Spring=1,Summer,Fall,Winter
}
/// <summary>
/// 9.2.1声明结构
/// </summary>
struct Time {
private int hours, mibutes, seconds;
public Time(int hh,int mm,int ss)
{
this.hours = hh % 24;
this.mibutes = mm % 60;
this.seconds = ss % 60;
}
public int Hours()
{
return this.hours;
}
}
}
}
/// <summary>
/// 第十章:使用数组
/// </summary>
namespace Capter10
{
class Program
{
static void Main(string[] args)
{
//10.1 声明数组变量
int[] pins;//还可以是结构、枚举或类
//10.2创建数组实例
pins = new int[4];
//10.3填充和使用数组
Random r = new Random();
int[] pins1 = new int[4] { r.Next() % 10, r.Next() % 10, r.Next() % 10, r.Next() % 10 };
///10.3.1 创建隐式类型的数组
var names = new[] { new { name = "jhon", age = 12 }, new { name = "aaa", age = 1 }, new { name = "bbbb", age = 2 }, new { name = "on", age = 10 } };
///10.3.2 访问单独的数组元素
for (int i = 0; i < pins1.Length; i++)
{
Console.WriteLine($"{pins1[i]}");
}
///10.3.3访问数组元素序列
//var subset = names[0...2];
//var subset = names[^3...4];后面三个元素
//^1=4-1 ^3=4-3
///10.3.4遍历数组
foreach(var name in names)
{
Console.WriteLine(name.ToString());
}
///10.3.5数组作为方法的参数和返回值
//10.4复制数组
//直接复制的话一方有改动另一方也会变动
pins = new int[]{ 9,8,6,5};
int[] copy = new int[pins.Length];
for(int i = 0; i < copy.Length; i++)
{
copy[i] = pins[i];
}
//或者
pins.CopyTo(copy,0);//从索引0开始
//或者
Array.Copy(pins, copy, copy.Length);
//或者
copy = (int[])pins.Clone();
//10.5使用多维数组
int[,] item = new int[4,6];
///创建交错数组
int[][] item1 = new int[4][];
int[] colum0 = new int[3];
item1[0] = colum0;
//10.6访问包含值类型的数组
Person[] faily = new[] { new Person("aaa", 57), new Person("bbb", 52), new Person("ccc", 55), new Person("ddd", 50) };
Person person = FindYoungest(faily);
Console.WriteLine($"{person.Name};{person.Age}");
Console.ReadLine();
}
/// <summary>
/// 寻找家里年龄最小的人
/// </summary>
/// <returns></returns>
public static Person FindYoungest(Person[] family)
{
int youngest = 0;
for (int i = 1; i < family.Length; i++)
{
if (family[i].Age < family[youngest].Age)
{
youngest = i;
}
}
return family[youngest];
}
}
}
namespace Capter10
{
class Person
{
public string Name;
public int Age;
public Person (String name,int age)
{
this.Name=name;
this.Age = age;
}
}
}