c#学习3,构造函数

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

namespace 构造函数1
{
class Program
{
static void Main(string[] args)
{
person p1 = new person();
person p2 = new person("tom");
person p3 = new person("emily",12);

Console.WriteLine("年龄:{0},姓名:{1}",p1.age,p1.name);
Console.WriteLine("年龄:{0},姓名:{1}",p2.age,p2.name);
Console.WriteLine("年龄:{0},姓名:{1}",p3.age,p3.name);
Console.ReadKey();
}
}
//构造函数用来创建对象,并且可以在构造函数中对对象进行初始化
//构造函数可以有参数,构建对象的时候传递函数参数即可
//构造函数可以重载,多个同名的构造函数,参数不同
//创建对象的时候进行初始化
//构造函数有利于对函数的封装
class person//构造函数没有返回值,函数名与类名一致
{
public string name { get; set; }//是属性的
public int age{set;get;}
public person()//没有参数的构造函数,默认是没有参数的函数
{
name = "未命名";
age = 0;

}
public person(string name)//没有参数的构造函数,默认是没有参数的函数
{
this.name = name;
}
public person(string name,int age)//没有参数的构造函数,默认是没有参数的函数
{
this.name = name;
this.age = age;
}
}
}

原文地址:https://www.cnblogs.com/cyychenyijie/p/3731095.html