Unity学习(C#)——属性的定义
public int MyIntProp{
get{
}
set{
}
}
定义需要名字和类型。
属性包括get和set两个块,并不⼀定要同时存在
取得属性的值,会访问属性中的get块,这个值类型必须和属性的类型⼀样。
给属性设置值,⽤set块,可以在set块中通过value访问已设置的值。
public Vector3(int x,int y,int z)
{
Console.WriteLine("构造函数2被调⽤了");
this.x = x;
this.y = y;
this.z = z;
}
public int MyIntProperty
{
get//没有get块不可以通过属性取值
{
Console.WriteLine("get块被调⽤");
return200;
}
set
{
Console.WriteLine("set块被调⽤");
Console.WriteLine("set块中访问的value的值是"+value);
}
}
static void Main(string[] args)
{
Vector3 v2 =new Vector3(1,2,3);
v2.MyIntProperty=500;//对属性设置值
int temp = v2.MyIntProperty;//调⽤属性值
Console.WriteLine(temp);
Console.ReadKey();
}
通过属性来访问字段
public float X
{
get{return x;}
set{ x =value;}
}
static void Main(string[] args)
{
Vector3 v2 =new Vector3(1,2,3);
v2.X =100;
Console.WriteLine(v2.X);
Console.ReadKey();
}
可以利⽤这个来进⾏校验⼯作
public int Age
{
set
{//通过set 在设置值前就可以做校验⼯作
if(value>=0)
{
age =value;
writeline函数}
}
}
设置属性的只读或只写
访问修饰符 private
public float X
{
get{return x;}
private set{ x =value;}//加private 使他只能在内部调⽤}
⾃动实现的属性
public float X{get;set;}
//上⽅代码和下⽅实现⼀样的功能⾃动实现
public float X
{
get{return x;}
set{ x =value;}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。