zl程序教程

您现在的位置是:首页 >  后端

当前栏目

方法重载和方法重写

方法重写 重载
2023-09-11 14:21:28 时间

一、C#语法规则:

方法重载:同一个类中,方法名相同,参数(类型或数量)不同,方法体不同;

方法重写:不同的类中,方法名相同,参数(类型和数量)相同,方法体不同;

关键字: vatiral(标注需要被重写的方法) 、override(标注用于重写的方法)

二、实践

1、方法重写

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



namespace _02Test
{

    class Program
    {

        static void Main(string[] args)
        {

            Teacher T1 = new Teacher();
            T1.Address();

            Myteacher M1 = new Myteacher();
            M1.Address();

            Console.ReadKey();
        }
    }

    public class Teacher
    {

        public virtual void Address()
        {
            Console.WriteLine("这是基类的虚方法!");
        }
    }

    public class Myteacher : Teacher //注意具有父子关系的类才能重写
    {

        public override void Address()
        {
            Console.WriteLine("这里重写基类的虚方法!");
        }
    }
}

 

方法的重载

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



namespace _02Test
{

    class Program
    {

        static void Main(string[] args)
        {

            Test T1 = new Test();
         
            Console.WriteLine(T1.Add(2));
            Console.WriteLine(T1.Add(1, 2));
            Console.WriteLine(T1.Add("3"));
            Console.WriteLine(T1.Add("3","5"));
            //  T1.Add(1,);//此时VS会自动提示有几个重载,选择一个你需要的。重载的目的就是适应多样的需要。

            Console.ReadKey();
        }
    }

    public class Test
    {

        public int Add(int i)
        {
            return i;
        }

        public int Add(int i,int j)
        {
            return i + j;
        }

        public string Add(string i)
        {
            return i ;
        }

        public string Add(string i,string j) 
        {
            return i + j; //此处加号起连接符作用
        }

    }

 
}