1.set和get访问器
set和get访问器 其实就是方法
set访问器:给字段设置值的方法,带一个参数,一般起成value, 把value赋值给字段、
get访问器:获取字段值的 带返回值的 return 字段;
如果对类里面的字段进行限制、或者拦截处理 ,可以在属性的set和get访问器里面进行条件设置。
在属性赋值的时候 set访问器执行了
在获取值的时候 get服务器执行了
People p1 = new People();
p1.Name = "嘉伟"; //在属性赋值的时候 set访问器执行了
p1.Age = 20;
Console.WriteLine(p1.Name+p1.Age+"-----------");//在获取值的时候 get服务器执行了
class People
{
//1 原始的set和get写法: 写私有的字段 再写公共属性,添加set和get
private string name;//私有的字段
public string Name //公共的属性, 目的在外部进行范围
{
get
{
//通过Name获取值 本质获取name的值
Console.WriteLine("11111111111111111");
return name+"视觉67班";
}
set
{
//设置值通过Name 给name进行赋值,value设置的值
Console.WriteLine("222222222222222222"+value);
value = "嘉伟";
name = value;
}
}
如果不想对属性进行任何操作 可以优化写法
private int id;
public int Id { get { return id; } set { id = value; } }
C#提供字段和属性的语法糖的写法,可以简写一句
public bool Sex { get;set; }
异常
throw new Exception("")-----抛出异常
Exception 是所有异常的基类
new DivideByZeroException("除数不能为0的异常")
System.StackOverflowException” 内存泄漏 死循环 方法自己调用自己
new IndexOutOfRangeException()//数组索引值超出范围异常
new ArgumentOutOfRangeException(); 参数超出范围的异常
2.构造函数
构造函数目的:创建对象,在构造函数给对象成员赋初始值
默认有一个无参数的构造函数, 类名与方法名一样,不要写有无返回值
也可以定义带参数的构造函数
public class Girls
{
public string Name { get; set; }
public string Hair { get; set; }
//无参数的构造函数
public Girls()
{
Name = "Baby";
Hair = "长头发";
}
}
定义有参数的构造函数:
public class Aircraft
{
public string Name { get; set; }
public string Type { get; set; }
public string Color { get; set; }
public string Company { get; set; } //公司
public int Speed { get; set; } //速度
public int Allcount { get; set; } //装载人数
public string PlaneType { get; set; } // 飞机类型 大中 小
public int Count { get; set; } //当前人数
private Random r = new Random();//随机数对象
//定义有参数的构造函数
public Aircraft(string n,string t,string c,string com,int s,int all)
{
Name = n;
Type = t;
Color = c;
Company = com;
Speed = s;
Allcount = all; // 传递100 200 400
Count = r.Next(0, Allcount); //当前人数
if (Allcount == 100 )
{
PlaneType = "小飞机";
}
else if (Allcount == 200)
{
PlaneType = "中飞机";
}else
{
PlaneType = "大飞机";
}
}
}
Aircraft a1 = new Aircraft("波音747","客机","白","波音公司",100,200);
Console.WriteLine(a1.Name+a1.Type+a1.Color+a1.Company+a1.Speed+a1.Allcount+a1.PlaneType+a1.Count);
3.析构函数
析构函数:当对象不使用时候,会把对象设置为null,再通过GC(垃圾回收机制)进行回收的时候 触发析构函数
析构函数的特点:方法名还是类名 只不过在方法名前加一个~
class People
{
public string Name { get; set; }
//析构函数:方法名还是类名 只不过在方法名前加一个~
~People()
{
Console.WriteLine(this.Name+"被释放了");
}
}
static void Main(string[] args)
{
People p1 = new People() { Name="zs"};
p1 = null; //把p1置为null
People p2 = new People() { Name = "李四" };
People p3 = p2;
p2 = null;
p3 = null;
Console.WriteLine("请按任意键进行回收");
Console.ReadKey(true);// 用户按键之后再往下执行
GC.Collect();//回收置为null内存空间
Console.ReadKey();
}

2076

被折叠的 条评论
为什么被折叠?



