C#学习之旅--Day07-枚举-类与对象

本文详细介绍了C#编程中的枚举(包括简单枚举、标志枚举和数据类型转换)、类与对象的概念、创建和操作,以及如何使用UserList类实现列表功能。通过实例展示了如何提高代码可读性和复用性。
摘要由CSDN通过智能技术生成

一、枚举

1.简单枚举

列举某种数据的所有取值。
作用:增强代码的可读性,限定取值。语法: enum名字{值1,值2,值3,值4}。
枚举元素默认为int,准许使用的枚举类型有byte、sbyte、short、ushort、int、uint、long或ulong.
每个枚举元素都是有枚举值。默认情况下,第一个枚举的值为0,后面每个枚举的值一次递增1,可以修改值,后面枚举数的值依次递增。

回顾2048,对移动方法统一起来

//不好 int值太多了
private static void Move(int[,] map,int direction)
{
    switch (direction)
    {
        case 0:
            UpMove(map);
            break;
        case 1:
            DownMove(map);
            break;
        case 2:
            LeftMove(map);
            break;
        case 3:
            RightMove(map);
            break;
    }
}

使用枚举,先创建类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Day05
{
    /// <summary>
    /// 定义枚举类型:移动方向
    /// </summary>
    enum MoveDirection
    {
        Up=0, 
        Down=1, 
        Left=2, 
        Right=3
    }
}

再使用

//枚举让可读型更强,限定调用者取值
private static void Move1(int[,] map, MoveDirection direction)
{
    switch (direction)
    {
        case MoveDirection.Up:
            UpMove(map);
            break;
        case MoveDirection.Down:
            DownMove(map);
            break;
        case MoveDirection.Left:
            LeftMove(map);
            break;
        case MoveDirection.Right:
            RightMove(map);
            break;
    }
}
static void Main()
{
    int[,] map = {
    { 2, 2, 4 ,0},
    { 2,  2,0,2 },
    { 0,2,4,2 },
    { 2,2,0 ,2 } };
    Move1(map, MoveDirection.Up);
    PrintDoubleArray(map);
}

2.标志枚举

需要同时赋值多个枚举

* 1.任意多个枚举值做 | 运算的结果不能与其他枚举值相同(值以2的n次幂递增)
* 2.定义枚举时,使用【flags】增加可读性

先创建类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Day07
{
    [Flags]
    enum PersonStyle
    {
        //tall = 1,                   //0000000000
        //rich = 2,                  //0000000001
        //handsome = 3,      //0000000010
        //white = 4,               //0000000011
        //beautiful = 5         //0000000100

        tall = 1,                   //0000000001
        rich = 2,                  //0000000010
        handsome = 4,      //0000000100
        white = 8,               //0000001000
        beautiful = 16        //0000010000
    }
    /*
     * 选择多个枚举值
     * 运算符|(按位或)两个对应的二进制位中有一个为1,结果位为1
     * tall | rich -->
     * 
     * 选择多个枚举的条件:
     * 1.任意多个枚举值做 | 运算的结果不能与其他枚举值相同(值以2的n次幂递增)
     * 2.定义枚举时,使用【flags】增加可读性
     * 
     * 判断标志枚举是否包含指定枚举值
     * 运算符&(按位与)
     * 
     */
}

清晰按位与按位或如何包含内容

static void Main()
{
    PrintPersonStyle(PersonStyle.tall | PersonStyle.rich);
}

private static void PrintPersonStyle(PersonStyle style)
{
    //如何判断包含
    if ((style & PersonStyle.tall) == PersonStyle.tall)
        Console.WriteLine("高");
    if ((style & PersonStyle.white) == PersonStyle.white)
        Console.WriteLine("白");
    if ((style & PersonStyle.beautiful) == PersonStyle.beautiful)
        Console.WriteLine("漂亮");
    if ((style & PersonStyle.rich) != 0)
        Console.WriteLine("有钱");
    if ((style & PersonStyle.handsome)!=0)
        Console.WriteLine("帅");
}

3.枚举数据类型转换

//数据类型转换
//int -->Enum
PersonStyle style01 = (PersonStyle)2;

PrintPersonStyle((PersonStyle)2);
//Enum-->int
int enumNumber = (int)(PersonStyle.tall | PersonStyle.white);

//sring-->Enum
//”beautiful“
PersonStyle style02 = (PersonStyle)Enum.Parse(typeof(PersonStyle), "beautiful");

//Enum--》string
string strEnum = PersonStyle.tall.ToString();

二、类与对象

类是一个抽象的概念,即为生活中的”类别”。
对象是类的具体实例,即归属于某个类别的”个体”。例如∶学生是一个类,表示一种类型,”八戒同学”则是一个对象。

名词类型的共性,作为数据成员。

动词类型的共性,作为方法成员。

1.创建类语法

访问级别 class 类名

{

        类成员.......

}

通常每个类都在一个独立的C#源文件中。

创建新的类意味着在当前项目产生了一种新的数据类型。

2.创建类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Day07
{
    /// <summary>
    /// 定义 老婆 类
    /// </summary>
    internal class Wife
    {
        //数据成员 访问级别是默认private
        private string name;
        private string sex;
        private int age;

        //方法成员
        public void SetName(string name)
        {
            //this 这个对象(引用)
            this.name = name;
        }

        public string GetName()
        {
            return name;
        }

        public void SetAge(int age)
        {
            this.age = age;
        }

        public int GetAge()
        {
            return this.age;
        }
    }
}

3.创建对象

语法:

类名 引用名

引用名 = new 构造函数(参数列表)

static void Main()
{
    //声明wife类型的引用
    Wife wife01;
    //指向Wife类型的对象(实例化Wife类型对象)
    wife01 = new Wife();
    wife01.SetName("令豪");
    wife01.SetAge(18);
    
    Console.WriteLine(wife01.GetName());
    Console.WriteLine(wife01.GetAge());
}

4.数据分配 

                         栈                                                                 堆

5.成员变量

定义在类中,方法外的变量

·特点:
--具有默认值。
--所在类被实例化后,存在堆中,对象被回收时,成员变量从堆中清除。
--可以与局部变量重名。

例如上例中Wife类中的name,sex,age

使用this.可以申明就是外部的成员变量

6.访问修饰符

private 私有      public  公有

设置成员时:public int age

在创建对象后,可以wife01.age = 80

为了对数据进行验证:设置为私有

private int age;

public void SetAge(int age)
{
    if (age <= 19 && age >= 18)
        this.age = age;
    else
        throw new Exception("我不要");
}

7.属性(首字母大写)

对字段起保护作用,可实现只读、只写功能

本质就是对字段的读取与写入方法

注意:1.通常一个公有属性对应一个私有的字段         2.属性只是外壳,实际上操作的私有字段

private string name   //老板
public string Name    //助理
{
    //读取时保护
    get { return name; } 
    //写入时保护 value是要设置的数据
    set { name = value; }
}

调用时

Wife wife03 = new Wife();
wife03.Name = "王喆";

8.构造函数

提供了创建对象的方式,常常用于初始化类的数据成员

一个类若没有构造函数,那么编译器会自动提供一个无参数构造函数

一个类若有构造函数,那么编译器不会提供一个无参数构造函数

本质:方法

特殊:没有返回值   与类同名  创建对象时自动调用

public Wife()
{
    Console.WriteLine("创建对象被执行了");
}

public Wife(string name):this()//调用无参数构造函数
{
    this.Name = name;
}
public Wife(string name, int age):this(name) //调用赋只赋name的构造函数
{
    //this.name = name;  构造函数如果为字段赋值,属性的代码块不会执行
    //this.Name = name;
    this.Age = age;
}

可以使用:this()进行继承

//如果不希望在类的外部被创建对象,就构造函数私有化
//private Wife()

Wife wife04 = new Wife();
Wife wife05 = new Wife("李轩");
Wife wife06 = new Wife("李轩",18);

9.总结

类结构

访问级别 class 类名

{

        字段:存储数据

        属性:保护字段

        构造函数:提供创建对象的方式,初始化类的数据成员

        方法:向类的外部提供某种功能

}

三、练习

1.查找年龄最小的老婆(返回Wife类型的引用)

static void Main()
{
    Wife w01 = new Wife();
    w01.Name = "01";
    w01.Age = 35;

    Wife w02 = new Wife("02",30);

    Wife[] wifeArray = new Wife[5];
    wifeArray[0] = w01;
    wifeArray[1] = w02;
    wifeArray[2] = new Wife("03", 40);
    wifeArray[3] = new Wife("04", 20);
    wifeArray[4] = new Wife("05", 25);

    //练习1:查找年龄最小的老婆(返回Wife类型的引用)
}
private static Wife GetWifeByMinAge(Wife[] wifeArray)
{
    Wife minwife = wifeArray[0];
    for (int i = 1; i < wifeArray.Length; i++)
    {
        if (minwife.Age> wifeArray[i].Age)
            minwife = wifeArray[i];
    }
    return minwife;
}

内存分配

2.添加UserList的类实现列表无法实现的功能

User类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Day07
{
    /// <summary>
    /// 用户类
    /// </summary>
    internal class User
    {
        //字段
        private string loginId;

        //属性  包含2个方法
        public string LoginId 
        { 
            get
            {  return this.loginId; }
            set 
            { this.loginId = value; } 
        }

        //自动属性 包含1个字段 2个方法
        public string Password { get; set; }   

        //构造函数
        public User()
        {

        }
        public User(string loginId,string pwd)
        {
            this.loginId = loginId;
            this.Password = pwd;
        }

        //方法
        public void PrintUser()
        {
            Console.WriteLine("账号:{0},密码:{1}",LoginId,Password);
        }
    }
}

//数组初始化 必须 指定大小
//User[] userArray = new User[?];
//读写元素 必须通过 索引
//userArray[?] = user01;

/*
 * 用户集合类 UserList
 * {
 *          private User[] data = null;  //真正储存用户的字段
 *          
 *          public UserList():this(8){}
 *          public UserList(int capacity)
 *          {
 *              data = new User[capacity]
 *          }
 *          
 *          public void Add(User value)
 *          {
 *              data[?]=value;
 *              //如果容量不够
 *              //扩容:开辟更大的数组   拷贝原始数据 替换引用
 *          }
 *          
 *          public User GetElement(int index)
 *          {
 *              return data[index]
 *          }
 *          
 *          插入功能  删除功能
 *  }
 *  使用:
 *  UserList list = new UserList(10)
 *  list.Add(u1)
 *  list.Add(u2)
 *  list.Add(u3)
 *  list.Add(u4)
 *  
 *  for(int i =0;i<list.Count;i++)
 *  {
 *      User user = list.GetElement(i);
 *      user.PrintUser();
 *   }
 */

UserList类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Day07
{
    internal class UserList
    {
        //*********字段***********
        private User[] data = null;
        private int currentCount;
        //*********属性***********
        public int Count { get { return currentCount; } }
        //*********构造函数***********
        public UserList():this(8){}

        public UserList(int capacity)
        {
            data = new User[capacity];
            currentCount = 0;
        }
        //*********方法***********
        public void Add(User user)
        {
            CheckCapacity();
            data[currentCount++] = user;
        }

        private void CheckCapacity()  //ctrl R M提取方法
        {
            if (currentCount >= data.Length)
            {
                User[] newData = new User[data.Length * 2];
                data.CopyTo(newData, 0);
                data = newData;
            }
        }

        public User GetElement(int index)
        {
            if (index >= 0 && index < currentCount)
            {
                return data[index];
            }
            throw new ArgumentOutOfRangeException(nameof(index), "Index is out of range.");
        }

        public void Remove(int index)
        {
            if (index < 0 || index >= currentCount)
            {
                throw new ArgumentOutOfRangeException(nameof(index), "Index is out of range.");
            }

            for (int i = index; i < currentCount - 1; i++)
            {
                data[i] = data[i + 1];
            }

            data[currentCount - 1] = null; 
            currentCount--;
        }

        public void Insert(int index, User item)
        {
            if (index < 0 || index >= currentCount)
            {
                throw new ArgumentOutOfRangeException(nameof(index), "Index is out of range.");
            }
            CheckCapacity();
            for(int i = currentCount;i> index; i--)
            {
                data[i] = data[i - 1];
            }
            data[index] = item;
            currentCount++;
        }
    }
}

调用UserList类

static void Main()
{
    UserList list = new UserList(10);
    User u1 = new User("wang","1");
    User u2 = new User("li", "12");
    User u3 = new User("zhao", "123");
    User u4 = new User("qin", "1234");

    list.Add(u1);
    list.Add(u2);
    list.Add(u3);
    list.Add(u4);

    for (int i = 0;i<list.Count;i++)
    {
        User user = list.GetElement(i);
        user.PrintUser();
    }
}

3.如果某个功能重复使用

可以Ctrl  R  M提取方法

  • 28
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秦果

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值