C#虚方法和抽象方法

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

namespace test0322
{
    public abstract class TestAbstract//抽象方法只能在抽象类中定义;虚方法则不是
    {
        public abstract void Run();

        //public abstract void Run1() { }//报错,抽象方法不能有实现

        public abstract int I1 { get; }//abstract可以用来修饰类,方法,属性,索引器
        public abstract string this[int index] { get; set; }
    }
    public class TestVirtual//抽象方法只能在抽象类中定义;虚方法则不是
    {
        // public abstract void Run();//报错,因抽象方法只能在抽象类中定义。

        //  public virtual void Run1();//报错,虚方法必需要有实现

        public virtual void Run2() { }//虚方法必需要有实现
        public virtual void Run3() { }//虚方法必需要有实现,不必需在子类重写.
        public virtual int I1 { get; }//virtual可以用来修饰类,方法,属性,索引器
        public virtual string this[int index] { get => ""; set => value = ""; }
    }
    public class abs : TestAbstract
    {
        public override string this[int index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

        public override int I1 => throw new NotImplementedException();

        public override void Run()//抽象方法必需再子类重写.
        {
            throw new NotImplementedException();
        }
    }
    public class vir : TestVirtual
    {
        public override void Run2()//虚方法不必需在子类重写.
        {
            throw new NotImplementedException();
        }
    }
    public class test
    {
        //TestAbstract testAbstract = new TestAbstract();//抽象父类不能实例
        TestAbstract testAbstract1 = new abs();

        TestVirtual testVirtual = new TestVirtual();
        TestVirtual testVirtual1 = new vir();

    }
}

 

posted @ 2024-03-26 09:00  奔赴山海Y  阅读(12)  评论(0)    收藏  举报