记录一下:
1.构造函数和析构函数:对对象进行初始化和回收对象资源。对象生命周期以构造函数开始,以析构函数结束。构造函数、析构函数与所在类具有相同名字,析构函数名前有(~),析构函数自动释放对象所占空间。
构造函数:
首先了解this保留字在类的构造函数中,this作为值类型,它表示对正在构造的对象本身的应用。
析构函数:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Person
{
public string name;
public int age;
public int hight;
//构造函数可以重载可以有多个,析构函数只有一个不可以重载,在函数全部运行后,析构函数自动调用。
public Person()
{
name = "吴yx";
age = 19;
hight = 162;
}
public Person(string name,int age,int hight)
{
this.name = "张yx";
this.age = 30;
this.hight = 177;
}
//系统默认构造函数
//public Person(){};
~Person ()
{
Console.WriteLine("析构函数调用");
}
}
class Program
{
public static void Main(string[] args)
{
Person t = new Person();//调用的是构造一。
//Person t=new Person("吴yx",18,160);调用的是构造二。
Console.WriteLine(t.name);
Console.WriteLine(t.age);
Console.WriteLine(t.hight);
Console.ReadKey();
}
}
}
2方法体外定义变量
class program
{
public static d;
public static e;
public static void jiafa(int a,int b){d=a+b;e=a*b;}//方法
static void main(string[]args)
{
program.jiafa(4,2);
Console.WriteLine(program.d);
Console.WriteLine(program.e);
Console.ReadKey();
}
}
3方法的重载
满足1方法名一样2方法列表不一样即可。(1类型2个数)
C#的乘法(重载)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Person
{
public int Sum(int a,int b)
{
return a * b;
}
public double Sum(double a, double b)
{
return a * b;
}
public int Sum(int a, int b, int c)
{
return a * b * c;
}
}
class Program
{
public static void Main(string[] args)
{
Person t = new Person();
Console.WriteLine(t.Sum(6.5,9.7));
Console.ReadKey();
}
}
}
4.类中可以赋所有初值、
namespace ConsoleApp3
{
class Person
{
public string name="tdytdfy";
public int age;
public double hight;
public double weight;
}
class Program
{
public static void Main(string[] args)
{
Person t = new Person();
t.name = "sda";
}
}
}