C#构造函数

Posted on 2008-04-10 16:47  xiao zhou  阅读(231)  评论(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();
            
           
            
        }

    }

}



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

 1using System.Collections.Generic;
 2using System.Text;
 3
 4namespace ConsoleApplication1
 5{
 6    class animal
 7    {
 8        public animal()
 9        {
10            Console.WriteLine("实例出动物");
11        }

12
13        public animal(string dog)
14        {
15            Console.WriteLine("实例出狗");
16        }

17
18       
19    }

20    class person : animal
21    {
22        public person():base("dog")
23        {
24           
25            Console.WriteLine("实例出人");
26        }

27       
28    }

29    class Program
30    {
31        static void Main(string[] args)
32        {
33            person p = new person();
34            
35           
36            
37        }

38    }

39}

40
41


 

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

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