二十八、C#中的结构、枚举、集合

1.结构struct

【定义一个老师结构】

namespace Demo11
{
    /// <summary>
    /// 老师结构 值类型,具体的,读取速度更快;结构字段不可以赋初始值;不能显示的去写一个不带参数的构造方法1
    /// </summary>
    public struct Teacher
    {
        public Teacher(string name,int age,string subject)
        {
            this.name = name;
            this.age = age;
            this.subject = subject;
        }
        public string name;
        public int age;
        public string subject;
        
        public void Xuexi()
        {

        }
    }
}

【定义一个学生类】

namespace Demo11
{
    /// <summary>
    /// 学生类 抽象的 去创建,分配空间;可以赋初始值;可以写构造方法,但名称固定,与类名相同
    /// </summary>
    public class Student
    {
        public Student()//构造方法作用:初始化信息
        { 
            
        }
        public string name = "匿名";
        public int age;
        public float score;
        public char sex;
    }
}

【定义一个班级管理类】

namespace Demo11
{
    /// <summary>
    /// 班级管理类
    /// </summary>
    public class ClassManager
    {
        Teacher teacher;//Teacher是具体的结构,已有内存
        //Teacher teacher =  new Teacher();也不会报错
        Student student = new Student();//Student是抽象的类,需要创建空间,用完释放
        public void Exam()
        {
            teacher.name = "张学友";
            student.name = "潘玮柏";
            Console.WriteLine($"老师{teacher.name}正在教{student.name}");
        }
    }
}

【在main()中调用】

namespace Demo11
{
    class Program
    {
        static void Main(string[] args)
        {
            ClassManager classManager = new ClassManager();
            classManager.Exam();
            Console.ReadLine();
        }
    }
}

 

2.枚举enum

①枚举是与“类”是一个级别的,需要创建;②可以直接点出来,应用于整个项目

【使用枚举】

class Program
{
    //枚举 值类型 默认static
    //枚举应用场景:不需要修改、固定的、常见的值
    /// <summary>
    /// 角色
    /// </summary>
    public enum Role
    {
        战士, 法师, 道士, GM
    }

    static void Main(string[] args)
    {
        Role role = Role.道士;
        switch (role)//快速方法:复制Role,点击default,可快速显示
        {
            case Role.战士:
                Console.WriteLine("我是战士");
                break;
            case Role.法师:
                Console.WriteLine("我是法师");
                break;
            case Role.道士:
                Console.WriteLine("我是道士");
                break;
            case Role.GM:
                Console.WriteLine("我是游戏管理员");
                break;
            default:
                Console.WriteLine("自定义职业");
                break;
        }
        Console.ReadLine();
    }
}

【使用数组】

public enum Role
{
    战士=1, 法师=2, 道士=3, GM=4
    //战士, 法师, 道士, GM
}

//数组可以修改数据
public static string[] Roles = { "战士", "法师", "道士", "GM" };

static void Main(string[] args)
{
     Console.WriteLine((int)Role.道士);
}

【遍历枚举】GetNames  GetValues

   检测类型 :   typeof()

//foreach(var item in Enum.GetNames(typeof(Role)))
foreach(var item in Enum.GetValues(typeof(Role)))
{
    Console.WriteLine(item);
}

 

3.集合

【创建一个学生类】

namespace Demo12
{
    public class Student
    {
        public string StuNo { get; set; }
        public string StuName { get; set; }
        public char Sex { get; set; }
        public int Age { get; set; }
    }
}

【创建一个老师类】

namespace Demo12
{
    public class Teacher
    {
        public string EmpNo { get; set; }
        public string Name { get; set; }
    }
}

【1】ArrayList    using System.Collections;

#region 方法一 ArrayList 增强版数组
public static void Method1()
{
    //ArrayList  底层逻辑是数组
    //变量 int age、int[] age
    Student stu1 = new Student() { StuNo = "C#1001", StuName = "张三", Sex = '男', Age = 19 };
    Student stu2 = new Student() { StuNo = "C#1002", StuName = "李四", Sex = '女', Age = 21 };
    Student stu3 = new Student() { StuNo = "C#1003", StuName = "王五", Sex = '男', Age = 21 };
    Teacher teacher1 = new Teacher() { EmpNo = "T1001", Name = "张学友" };

    Student[] students = new Student[30];//创建数组 固定长度 不能减少 不能增加   执行效率高 
    students[0] = stu1;
    students[1] = stu2;
    //students[2] = teacher1;//编译错误

    ArrayList studentArray = new ArrayList();//创建集合 可变长度
    //添加
    studentArray.Add(stu1);
    studentArray.Add(stu2);
    studentArray.Add(stu3);
    studentArray.Add(teacher1);//基类不会报错
    //删除
    studentArray.Remove(stu2);//通过对象删除
    //studentArray.RemoveAt(1);//通过下标删除


    //不安全:放进去时比较任意,但是取出时就要考虑类型
    foreach (var item in studentArray)
    {
        if (item is Student)
        {
            Student stu = (Student)item;
            Console.WriteLine($"{stu.StuName}--{stu.Sex}");
        }
        else if (item is Teacher)
        {
             Teacher t = (Teacher)item;
             Console.WriteLine($"{t.EmpNo}--{t.Name}");
        }
    }
}
#endregion
/// <summary>
/// 集合是数组的升级版
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
     Method1();
}

优点:存放任意类型

缺点:由于可以存放任意类型,或导致装箱拆箱的性能损耗;不安

数组与集合的修改:(用for循环)

若要打印,用foreach循环

//数组的修改
students[2] = stu3;
Student stu4 = students[2];
stu4.Age = 20;

//集合的修改
//使用时要先转化成对应的类型,因为默认是Object类型
Student stu5 = (Student)studentArray[2];
stu5.StuName = "张三丰";

ArrayList.RemoveAt(index);//删除指定索引类型的对象

ArrayList.Clear();//清除集合内的所有元素

【2】Hashtable 哈希表

ArrayList与Hashtable的相同点:存放的都是object

#region 方法二 哈希表 key value
public static void Method2()
{
    Student stu1 = new Student() { StuNo = "C#1001", StuName = "张三", Sex = '男', Age = 19 };
    Student stu2 = new Student() { StuNo = "C#1002", StuName = "李四", Sex = '女', Age = 21 };
    Student stu3 = new Student() { StuNo = "C#1003", StuName = "王五", Sex = '男', Age = 21 };
    Teacher teacher1 = new Teacher() { EmpNo = "T1001", Name = "张学友" };

    Hashtable ht = new Hashtable();//键值对集合 无序集合 KEY VALUE
    //添加
    ht.Add("zs", stu1);
    ht.Add("ls", stu2);
    ht.Add("ww", stu3);
    ht.Add("lcw", teacher1);

    Student stu4 = (Student)ht["zs"];
    //Student stu5 = (Student)ht["lcw"];//错误
    //as 兼容性转换(异常处理机制)
    Student stu6 = ht["lcw"] as Student;//如果不能转换成Student类型,则返回空值,但是不会报错

    //修改
    stu4.StuName = "张三丰";

    //删除 通过自定义的key删除
    ht.Remove("ls");

    //循环遍历
    //遍历value
    foreach (var item in ht.Values)
    {
        if (item is Student)
        {
            Student stu = (Student)item;
            Console.WriteLine($"{stu.StuName}   {stu.Sex}");
        }
        else if (item is Teacher)
        {
            Teacher t = (Teacher)item;
            Console.WriteLine($"{t.EmpNo}   {t.Name}");
        }
    }
    //遍历key
    foreach (var item in ht.Keys)
    {
        Console.WriteLine(item);
    }
    Console.ReadLine();
}
#endregion

【3】List<T>  泛型集合

#region 方法三 泛型集合 List<T> 增强版数组
public static void Method3()
{
    //List<T>泛型集合优点:数组 + ArrayList ;不需要做任何装箱、拆箱,数据类型转化(安全)
    Student stu1 = new Student() { StuNo = "C#1001", StuName = "张三", Sex = '男', Age = 19 };
    Student stu2 = new Student() { StuNo = "C#1002", StuName = "李四", Sex = '女', Age = 21 };
    Student stu3 = new Student() { StuNo = "C#1003", StuName = "王五", Sex = '男', Age = 21 };
    Teacher teacher1 = new Teacher() { EmpNo = "T1001", Name = "张学友" };
    
    //类型限制(数据安全)
    List<Student> list = new List<Student>();
    //添加
    list.Add(stu1);
    list.Add(stu2);
    list.Add(stu3);
    
    //读取和修改
    Student stu4 = list[0];
    stu4.StuName = "姚雪";
    
    //删除
    list.RemoveAt(1);
    //list.Remove(stu4);

    //list.Add(teacher1);//错误
    //遍历数据
    foreach (var item in list)
    {
        Console.WriteLine(item.StuName+"---"+item.Sex);
    }
    Console.ReadLine();
}
#endregion

【4】Dictionary<>  泛型数组集合

#region 方法四 泛型数组集合 dictionary
public static void Method4()
{
    Student stu1 = new Student() { StuNo = "C#1001", StuName = "张三", Sex = '男', Age = 19 };
    Student stu2 = new Student() { StuNo = "C#1002", StuName = "李四", Sex = '女', Age = 21 };
    Student stu3 = new Student() { StuNo = "C#1003", StuName = "王五", Sex = '男', Age = 21 };
    Teacher teacher1 = new Teacher() { EmpNo = "T1001", Name = "张学友" };

    Dictionary<string, Student> dict = new Dictionary<string, Student>();

    //添加
    dict.Add("zs", stu1);
    dict.Add("ls", stu2);
    dict.Add("ww", stu3);
    //删除
    dict.Remove("ls");
    //查找并修改
    Student stu4 = dict["zs"];
    stu4.StuName = "小李";

    //遍历key
    foreach (var item in dict.Keys)
    {
        Console.WriteLine(item);
    }
    //遍历value
    foreach (var item in dict.Values)
    {
        Console.WriteLine(item.StuName+"---"+item.Sex);
    }
    Console.ReadLine();
}
#endregion

 

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 点我我会动 设计师:上身试试 返回首页