C#学习笔记(十六):索引器和重载运算符

C#学习笔记(十六):索引器和重载运算符_第1张图片

二维数组如何映射到一维数组

C#学习笔记(十六):索引器和重载运算符_第2张图片

重载运算符
1、算术运算符
2、关系运算符, < 和 > 成对重载
C#学习笔记(十六):索引器和重载运算符_第3张图片

C#学习笔记(十六):索引器和重载运算符_第4张图片

C#学习笔记(十六):索引器和重载运算符_第5张图片

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace m1w4d2_indexes
{
    #region 索引器-李索
    //索引器可以让我们通过不同的索引号返回对应类型的多个属性
    //索引器适用于除自动属性以外的所有属性特性
    //索引号可以是任意类型
    //索引器在通过类对象来访问和赋值 变量(类对象)[索引号]
    //访问修饰 返回类型 this[索引号,索引号,索引号,索引号......]
    //{ get {return} set {value} }
    //用索引器访问一个怪物类中的不同字段
    class Monster
    {
        public Monster(int attack, int defend, int health, int speed, string name)
        {
            this.attack = attack;
            this.defend = defend;
            this.health = health;
            this.speed = speed;
            this.name = name;
        }
        int attack;
        int defend;
        int health;
        int speed;
        string name;
        //public string this[int indexa, int indexb]
        //{
        //    get { return ""; }
        //    set { }
        //}
        public string this[int index]
        {
            get
            {
                string str = "";
                switch (index)
                {
                    case 0: str = attack.ToString(); break;
                    case 1: str = defend.ToString(); break;
                    case 2: str = health.ToString(); break;
                    case 3: str = speed.ToString(); break;
                    case 4: str = name; break;
                }
                return str;
            }
            set
            {
                switch (index)
                {
                    case 0: attack = int.Parse(value); break;
                    case 1: defend = int.Parse(value); break;
                    case 2: health = int.Parse(value); break;
                    case 3: speed = int.Parse(value); break;
                    case 4: name = value; break;
                }
            }
        }
    }
    #endregion
    #region 多维度的索引号
    //索引号可以任意维度
    //用一个MyArray类去模拟一个二维数组
    class MyArray
    {
        public MyArray(int x, int y)
        {
            //这个放元素的一维数组多长
            //array = new int[10];
            array = new int[x * y];//一维数组的长度
            Length = new int[2];
            Length[0] = x;
            Length[1] = y;
        }
        int[] Length;
        int[] array;
        public int GetLength(int index)
        {
            if (index > Length.Length)
            {
                throw new IndexOutOfRangeException();//抛异常
            }
            return Length[index];
        }
        public int this[int x, int y]
        {
            get
            {
                //我给你一个二维的下标,你如何映射到一维数组上
                return array[x + y * GetLength(0)];
            }
            set
            {
                array[x + y * GetLength(0)] = value;
            }
        }
    }
    #endregion
    #region 索引器-沈军
    class Unity1803
    {
        // C# 单例模式   (单独的实例)
        private static Unity1803 instance = null;
        public static Unity1803 Instance
        {
            get
            {
                if (instance == null) instance = new Unity1803();
                return instance;
            }
        }
        //静态构造函数什么时候调用
        //当我们访问静态成员的时候,先调用且只调用一次
        //当我们创建对象的时候,先调用且只调用一次
        //可以对静态字段做初始化使用的,静态的成员才会加载到内存中
        //static Unity1803()//静态构造函数,不能有访问修饰符和参数
        //{
        //    Console.WriteLine("调用静态构造函数");
        //}
        public int Count { private set; get; }    //
        Student[] students = new Student[37];   // null
        private Unity1803()
        {
            students[0] = new Student("蔡浩", 18, 90);
            Count++;
            students[1] = new Student("江灿荣", 20, 50);
            Count++;
            students[2] = new Student("贺益民", 18, 70);
            Count++;
        }
        public Student this[int index]
        {
            get
            {
                return students[index];
            }
            set
            {
                if (students[index] == null) Count++;
                students[index] = value;
            }
        }
        public Student this[string name]
        {
            get
            {
                for (int i = 0; i < Count; i++)
                {
                    if (students[i].Name == name)
                    {
                        return students[i];
                    }
                }
                return null;
            }
            set
            {
                students[Count] = new Student(name, 20, 80);
            }
        }
    }
    class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public int CSharpScore { get; set; }
        public Student(string name, int age, int score)
        {
            this.Name = name;
            this.Age = age;
            this.CSharpScore = score;
        }
        public override string ToString()
        {
            return "Name:" + Name + ", Age :" + Age + ", Score :" + CSharpScore;
        }
        public static bool operator >(Student lfs, int score)
        {
            return lfs.CSharpScore > score;
        }
        public static bool operator <(Student lfs, int score)
        {
            return lfs.CSharpScore < score;
        }
        public static bool operator true(Student s)
        {
            return s.CSharpScore >= 60;
        }
        public static bool operator false(Student s)
        {
            return s.CSharpScore < 60;
        }
        // 隐式类型转换 把字符串隐式的转换成Student类型
        public static implicit operator Student(string name)
        {
            Student s = new Student(name, 18, 75);
            return s;
        }
        // 显式类型转换 把Student类型强转成字符串
        public static explicit operator string(Student s)
        {
            return s.Name;
        }
    }
    #endregion
    class Program
    {
        static void Main(string[] args)
        {
            #region 索引器-李索
            Monster monster = new Monster(10, 5, 100, 5, "哥布林");
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(monster[i]);
            }
            Console.WriteLine();
            //把一个策划文档的数据切割成对应的字符数组
            //序列化
            string dataTitle = "attack,defend,health,speed,name";
            string data = "100,15,500,1,蠕虫皇后";
            string[] datas = data.Split(',');
            for (int i = 0; i < 5; i++)
            {
                monster[i] = datas[i];
            }
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(monster[i]);
            }
            #endregion
            #region 多维度的索引号
            //索引号可以任意维度
            //用一个MyArray类去模拟一个二维数组
            MyArray myArray = new MyArray(5, 7);
            for (int x = 0; x < myArray.GetLength(0); x++)
            {
                for (int y = 0; y < myArray.GetLength(1); y++)
                {
                    myArray[x, y] = x * 100 + y;
                }
            }
            for (int y = 0; y < myArray.GetLength(1); y++)
            {
                for (int x = 0; x < myArray.GetLength(0); x++)
                {
                    Console.Write(myArray[x, y] + "\t");
                }
                Console.WriteLine();
            }
            #endregion
            #region 索引器-沈军
            // 属性   操作字段
            // 索引器 对于操作集合的一种封装
            //Unity1803 unity1803 = new Unity1803();
            //unity1803[2] = new Student("沈天宇", 20, 95);
            for (int i = 0; i < Unity1803.Instance.Count; i++)
            {
                if (Unity1803.Instance[i])
                {
                    Console.WriteLine(Unity1803.Instance[i]);    // .ToString()方法
                }
            }
            Unity1803.Instance[Unity1803.Instance.Count] = "丁超";     // 隐式类型转换
            string name = (string)Unity1803.Instance[0];               // 显式类型转换
            //Console.WriteLine(unity1803["沈天宇"]);
            //Unity1803 _unity1803 = new Unity1803();
            //Console.WriteLine(Unity1803.Count);
            //Unity1803.instance = new Unity1803();  // 只读的
            //Unity1803 u1 = new Unity1803();       // 不允许的
            //Console.WriteLine(Unity1803.Instance[0]);
            // 隐式转换 显式转换
            int num1 = 100;
            byte num2 = 200;
            num1 = num2;        // 隐式类型转换
            num2 = (byte)num1;  // 显式类型转换
            #endregion
        }
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace m1w4d2_operator
{
    #region 练习1
    //通过重载运算符,我们可以给自定类型,增加计算功能
    struct Point2D
    {
        public int x, y;
        public Point2D(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
        public static Point2D Up = new Point2D(0, -1);
        public static Point2D Down = new Point2D(0, 1);
        public static Point2D Left = new Point2D(-1, 0);
        public static Point2D Right = new Point2D(1, 0);
        //返回类型?,函数名(operator 运算符)?参数?
        //public static i = i + 1;
        //两个参数,任意类型
        //返回类型,任意类型
        //算数运算符 是双目运算符,参数必须是两个,任意类型,返回类型,任意类型
        public static Point2D operator +(Point2D a, Point2D b)
        {
            return new Point2D(a.x + b.x, a.y + b.y);
        }
        public static Point2D operator -(Point2D a, Point2D b)
        {
            return new Point2D(a.x - b.x, a.y - b.y);
        }
        //关系运算符 是双目运算符,参数必须是两个,任意类型,返回类型是bool
        public static bool operator ==(Point2D a, Point2D b)
        {
            return a.x == b.x && a.y == b.y;
        }
        public static bool operator !=(Point2D a, Point2D b)
        {
            return !(a == b);
        }
        public override string ToString()
        {
            return string.Format("[x:{0},y{1}]", x, y);
        }
    }
    #endregion
    #region 练习2
    class Item
    {
        public static string style = "剑刀盾斧药";
        public Item(string name, int value)
        {
            this.name = name;
            this.value = value;
        }
        string name;
        int value;
        public override string ToString()
        {
            return string.Format("{0}:value:{1}", name, value);
        }
    }
    class Monster
    {
        public static Random roll = new Random();
        public int attack;
        public string name;
        public int speed;
        public Monster(int attack, int speed, string name)
        {
            this.attack = attack;
            this.name = name;
            this.speed = speed;
        }
        public static Item operator +(Monster a, Monster b)
        {
            string name = a.name.Substring(a.name.Length / 2) + b.name.Substring(b.name.Length / 2) + Item.style[roll.Next(0, Item.style.Length)];
            int value = (a.attack + b.attack) * 10 + a.speed + b.speed;
            if (name[name.Length - 1] == '')
            {
                value /= 10000;
            }
            return new Item(name, value);
        }
        public override string ToString()
        {
            return string.Format("{0}:attack:{1},speed:{2}", name, attack, speed);
        }
    }
    #endregion
    class Program
    {
        static void Main(string[] args)
        {
            #region 练习1
            //老位置
            Point2D oldPosition = new Point2D(5, 5);
            //position.x += dir.x;
            //新位置 是老位置 向上走一步
            Console.WriteLine(oldPosition);
            Point2D newPosition = oldPosition + Point2D.Up;
            Console.WriteLine(newPosition);
            //请问,新位置在老位置的哪个方向
            string dirStr = "";
            Point2D pointDir = newPosition - oldPosition;
            if (pointDir == Point2D.Up) dirStr = "";
            else if (pointDir == Point2D.Down) dirStr = "";
            else if (pointDir == Point2D.Left) dirStr = "";
            else if (pointDir == Point2D.Right) dirStr = "";
            Console.WriteLine("你的前进方向是{0}", dirStr);
            #endregion
            #region 练习2
            Monster a = new Monster(1000, 50, "哥布林");
            Monster b = new Monster(1000, 200, "索尼克");
            Console.WriteLine(a);
            Console.WriteLine(b);
            Item item = a + b;
            Console.WriteLine(item);
            #endregion
        }
    }
}

 

转载于:https://www.cnblogs.com/cnwuchao/p/10362502.html

你可能感兴趣的:(C#学习笔记(十六):索引器和重载运算符)