【C#】之使用泛型集合管理對象

首先定義個Weapon類:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Monkey泛型
{
    class Weapon
    {
        private int id;
        private string name;
        private int attack;
        /// <summary>
        /// 屬性列表
        /// </summary>
        public int Id
        {
            get { return id; }
            set { id = value; }
        }
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public int Attack
        {
            get { return attack; }
            set { attack = value; }
        }
        //構造函數
        public Weapon(int id,string name,int att)
        {
            this.id = id;
            this.name = name;
            this.attack = att;
        }
        /// <summary>
        /// 重寫tostring方法之後,在執行console.writeline方法時,就會按此執行
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            //使用字符串類的格式化方法,使用佔位符的方式{0},{1},{2}按照數字進行匹配
            return string.Format("id={0}...name={1}...attack={2}", id, name, attack);
        }
    }
}


在主函數中,進行對象實例化,泛型集合添加等操作:

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

namespace Monkey泛型
{
    class Program
    {
        static void Main(string[] args)
        {
            //定義武器集合
            List<Weapon> weapons = new List<Weapon>();

            //實例化武器,在Weapon類中已經定義
            Weapon w1 = new Weapon(1, "AK47", 100);
            //將武器添加到武器集合中
            weapons.Add(w1);

            //實際開發過程中一般用這種,效率高,簡潔
            weapons.Add(new Weapon(2, "倚天劍", 500));
            weapons.Add(new Weapon(3, "屠龍刀", 700));

            //通過索引刪除
           // weapons.RemoveAt(2);

            //在實際開發過程中,很難知道索引的值,最直接的想法是通過名字進行刪除
            //於是可以先遍歷集合,通過判斷元素名字進行刪除
            for (int i = 0; i < weapons.Count;i++ )
            {
                if (weapons[i].Name == "倚天劍")
                    weapons.Remove(weapons[i]);
            }

                //遍歷集合,打印內容
                for (int i = 0; i < weapons.Count; i++)
                    Console.WriteLine(weapons[i]);

            Console.ReadKey();
        }
    }
}

發佈了136 篇原創文章 · 獲贊 25 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章