TQC+ C# 認證教學手冊

306、樂透號碼(使用繼承)

參考程式碼

Program.cs

using System;
using System.Linq;
using System.Collections.Generic;

namespace CSD03
{
    class Program
    {
        static void Main(string[] args)
        {
            TaiwanLottory lot = new TaiwanLottory();
            TaiwanBigLottory bigLot = new TaiwanBigLottory();

            Console.WriteLine(" === TAIWAN LOTTORY ===");

            int[] nums = lot.GetLottorySequence().ToArray();

            Console.WriteLine("{0:00} {1:00} {2:00} {3:00} {4:00} {5:00} S:{6:00}",
                nums[0], nums[1], nums[2], nums[3], nums[4], nums[5], nums[6]);

            Console.WriteLine(" === TAIWAN BIG LOTTORY ===");

            nums = bigLot.GetLottorySequence().ToArray();

            Console.WriteLine("{0:00} {1:00} {2:00} {3:00} {4:00} {5:00} S:{6:00}",
                nums[0], nums[1], nums[2], nums[3], nums[4], nums[5], nums[6]);

            Console.ReadKey();
        }
    }
}

LottoryBase.cs

using System;
using System.Collections.Generic;

namespace CSD03
{
    public abstract class LottoryBase
    {
        protected IEnumerable<int> GetLottoryNumberSequence(int Min, int Max, int Length)
        {
            List<int> numbers = new List<int>();
            Random rnd = new Random();

            while (numbers.Count < Length)
            {
                int number = 0;

                do
                {
                    number = rnd.Next(Min, Max);
                }
                while (numbers.Contains(number));

                numbers.Add(number);
            }

            return numbers;
        }

        public abstract IEnumerable<int> GetLottorySequence();
    }
}

TaiwanLottory.cs

using System;
using System.Collections.Generic;

namespace CSD03
{
    class TaiwanLottory : LottoryBase
    {
        public override IEnumerable<int> GetLottorySequence()
        {
            return GetLottoryNumberSequence(1, 42, 7);
        }
    }
}

TaiwanBigLottory.cs

using System;
using System.Collections.Generic;

namespace CSD03
{
    class TaiwanBigLottory : LottoryBase
    {
        public override IEnumerable<int> GetLottorySequence()
        {
            return GetLottoryNumberSequence(1, 49, 7);
        }
    }
}