C#學習4

Cambridge發表於2012-08-21

函式的過載,及同一個類中方法名相同,引數列表不同,引數列表不同包括方法中的引數個數不同或引數的資料型別不同

首先說一種常見的過載,修改引數的個數和資料型別

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace chongzai
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            p.run();
        }
        void run()
        {
            int arg1 = 10;
            float arg2 = 12.5f;
            int arg3 = 30;
            dowork(arg1, arg2);
            dowork(arg1, arg2, arg3);
            dowork(arg2, arg3);
        }
        void dowork(int intdata, float floatdata, int moreintdata)
        {
            Console.WriteLine("intdata:{0},floatdata:{1},moredata:{2}", intdata, floatdata, moreintdata);
        }
        void dowork(int intdata, float floatdata)
        {
            Console.WriteLine("intdata:{0},floatdata:{1}", intdata, floatdata);
        }
        void dowork(float floatdata, int moreintdata)
        {
            Console.WriteLine("floatdata:{0},moreintdata:{1}", floatdata, moreintdata);
        }
    }
}

也可以通過給引數賦上預設值來進行過載,注意沒有預設值的引數寫在前面,有預設值的引數寫在後面

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace chongzai
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            p.run();
        }
        void run()
        {
            int arg1 = 10;
            float arg2 = 12.5f;
            int arg3 = 30;
            dowork(arg1);
            dowork(arg1, arg2);
            dowork(arg1, arg2, arg3);
            dowork();
        }
        void dowork(int intdata=0, float floatdata=0.0f, int moreintdata=0)
        {
            Console.WriteLine("intdata:{0},floatdata:{1},moredata:{2}", intdata, floatdata, moreintdata);
        }
     }
}

還也通過指定引數的傳值來過載

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace chongzai
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            p.run();
        }
        void run()
        {
            int arg1 = 10;
            float arg2 = 12.5f;
            int arg3 = 30;
            dowork(arg1);
            dowork(moreintdata:arg3);
            dowork(arg1, arg2);
            dowork(floatdata:arg2,moreintdata:arg3);
            dowork(arg1, arg2, arg3);
            dowork();
        }
        void dowork(int intdata=0, float floatdata=0.0f, int moreintdata=0)
        {
            Console.WriteLine("intdata:{0},floatdata:{1},moredata:{2}", intdata, floatdata, moreintdata);
        }
     }
}