构造函数
构造函数主要是用来创建对象时为对象赋初值来初始化对象。总与new运算符一起使用在创建对象的语句中 。A a=new A();
构造函数具有和类一样的名称;但它是一个函数具有函数的所有特性,同一个类里面可以有多个参数不同的构造函数,也就是函数的多态。
构造函数是在实例化类时最先执行的方法,通过这个特性可以给对象赋初值。
构造函数没有返回值,也不能用void修饰,只有访问修饰符。
每个类中都会一个构造函数,如果用户定义的类中没有显式的定义任何构造函数,编译器就会自动为该类型生成默认构造函数,类里面没有构造函数也可以,系统会为你自动创建无参构造函数。
构造函数代码练习
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 构造函数
{
class Program
{
static void Main(string[] args)
{
person person = new person("xx", 18, "男");
Console.WriteLine(person.name+person.age+person.sex);
Console.ReadKey();
}
}
class warface{
public warface(string name,int age) {
this.name = name;
this.age = age;
}
public string name;
public int age;
public string sex;
}
// 构造函数不能被继承,
//子类中的构造函数会默认调用父类无参数的构造函数
//不修改父类,而是在子类的构造函数后面通过base(),调用父类的构造函数
//:base("xx","11")调用父类构造函数
class person : warface {
public person(string name,int age,string sex):base(name,age)
{
this.sex = sex;
}
}
}
this调用自己的构造函数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace this调用自己的构造函数
{
class Program
{
static void Main(string[] args)
{
}
}
public class Person
{
public Person(string name, int age, string email, double salary)
{
this.Name = name;
this.Age = age;
this.Email = email;
this.Salary = salary;
}
//this作用1:在当前类的构造函数后面通过:this来调用当前类自己的其他构造函数。
public Person(string name)
: this(name, 0, null, 0)
{
// this.Name = name;
}
public Person(string name, int age)
: this(name, age, null, 0)
{
//this.Name = name;
//this.Age = age;
}
public Person(string name, string email)
: this(name, 0, email, 0)
{
//this.Name = name;
//this.Email = email;
}
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
public string Email
{
get;
set;
}
public double Salary
{
get;
set;
}
}
}