C# 构造函数

Posted on 2008-04-10 16:41  xiao zhou  阅读(163)  评论(0)    收藏  举报
    派生类调用构造函数的过程。  

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class animal
    {
        public animal()
        {
            Console.WriteLine("实例出动物");
        }

      
    }
    class person : animal
    {
        public person()
        {
          
            Console.WriteLine("实例出人");
        }
      
    }
    class Program
    {
        static void Main(string[] args)
        {
            person p = new person();
           
          
           
        }
    }
}

运行的结果为: 实例出动物
                     实例出人
说明构派生类是调用基类的构造函数。

using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class animal
    {
        public animal()
        {
            Console.WriteLine("实例出动物");
        }

        public animal(string dog)
        {
            Console.WriteLine("实例出狗");
        }

      
    }
    class person : animal
    {
        public person():base("dog")
        {
          
            Console.WriteLine("实例出人");
        }
      
    }
    class Program
    {
        static void Main(string[] args)
        {
            person p = new person();
           
          
           
        }
    }
}

如果,父类的构造函数有重载的话,如果没指定调用基类的那个构造函数,则调用默认的
如果,想调用指定的 用关键字 base。







博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3