对于构造方法的简单代码示例

本来不应该贴在这里的,会被众多高手贻笑大方的。不过,有两个同事这两天问我这个问题,我感觉大家的基础知识还不扎实,所以就把一个简单的demo放出来。加之这个站点也有很多非博客的人来看,权作一个新手入门。

using System;

namespace Construture
{
    
class Demo
    
{
        [STAThread]
        
static void Main(string[] args)
        
{
            Child c 
= new Child(10,20,30);
        }

    }


    
public class Parent
    
{
        
public Parent(int i)
        
{
            Console.WriteLine(
"Parent with 1 paramenter:"+i);
        }

    }


    
public class Child : Parent
    
{
        
public Child(int i,int j):base(j)
        
{
            Console.WriteLine(
"Child with 2 parameters:"+i);
            Console.WriteLine(
"Child with 2 parameters:"+j);
        }


        
public Child(int i,int j,int k):this(j,k)
        
{
            Console.WriteLine(
"Child with 3 parameters:"+i);
            Console.WriteLine(
"Child with 3 parameters:"+j);
            Console.WriteLine(
"Child with 3 parameters:"+k);
        }

    }

}


没有加析构函数,只要把析构理解为上面的反向就行了。
同事主要问我,:this(some parameter)和base(some parameter)是什么意思。我也没告诉他们,作了这么一个demo,自己运行一下,就知道接过了。如果愿意的话,F11跟踪每一步,效果会更好一些。
原文地址:https://www.cnblogs.com/juqiang/p/21763.html