栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

√ C# - 16.怎么重写基类(P232)

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

√ C# - 16.怎么重写基类(P232)

  1. C#支持重写实例方法和属性,不支持重写字段和静态成员。
  2. 基类必须使用关键字virtual标记允许重写的成员,派生类必须使用关键字override标记被重写的成员。
  3. 被重写的成员仍然是虚成员,仍然可以被派生类继续重写。
  4. 若要中止某一成员继承链,则使用关键字new修饰该成员,这样该成员自此由虚转实,不可以再被派生类重写。
using System;

namespace _16
{
    class Program
    {
        static void Main(string[] args)
        {
            Test1 test1 = new Test1();
            Test1 test2 = new Test2();
            Test1 test3 = new Test3();

            Console.WriteLine("*****测试override*****");
            test1.Print1();
            test2.Print1();
            test3.Print1();
            Console.WriteLine();

            Console.WriteLine("*****测试new*****");
            test1.Print2();
            test2.Print2();
            test3.Print2();
            Console.WriteLine();
        }
    }

    class Test1
    {
        public virtual void Print1()
        {
            Console.WriteLine("Test1");
        }

        public virtual void Print2()
        {
            Console.WriteLine("Test1");
        }
    }

    class Test2 : Test1
    {
        public override void Print1()
        {
            Console.WriteLine("Test2");
        }

        public new void Print2()
        {
            Console.WriteLine("Test2");
        }
    }

    class Test3 : Test2
    {
        public override void Print1()
        {
            Console.WriteLine("Test3");
        }

        public new void Print2()
        {
            Console.WriteLine("Test3");
        }
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/906215.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号