unity3D-游戏/AR/VR在线就业班 C#入门属性学习笔记
点击观看视频学习:http://edu.csdn.NET/lecturer/107
属性
属性自动帮我们给字段添加Get和Set方法
属性本质上也是Set和Get方法,只是形式不同
namespace Lesson_07
{
class MainClass
{
public class Person{
private string name;
//name 的Get方法
// public string GetName(){
// return name;
// }
//name 的Set方法
// public string SetName(string value){
// name=value;
// }
//访问修饰符 属性类型 属性名 (set(……);get(……))
public string Name{
//Get访问起
get{
return name;
}
//Set访问起
set{
//value 关键字只有在属性的Set中有意义,表示外界传递过来的值
name = value;
}
}
}
public static void Main (string[] args)
{
Person p = new Person ();
// p.SetName ("lanou");
// Console.WriteLine (p.GetName());
p.Name = "lanou";
Console.WriteLine (p.Name);
}
}
}
访问器
属性中的Set和Get称作访问器
Get访问器用来读取属性的值,相当于Get方法
Set访问器用来设置属性的值,相当于Set方法
只有Set访问器的属性叫做只写属性
只有Get访问器的属性叫做只读属性
同时具有两个访问器的属性叫读写属性
using System;
namespace Lesson_07
{
class MainClass
{
public class Person{
private string name;
//name 的Get方法
// public string GetName(){
// return name;
// }
//name 的Set方法
// public string SetName(string value){
// name=value;
// }
//访问修饰符 属性类型 属性名 (set(……);get(……))
public string Name{
//Get访问起
get{
return name;
}
//Set访问起
set{
//value 关键字只有在属性的Set中有意义,表示外界传递过来的值
name = value;
}
}
//只读属性
private int age=18;
//只读属性,只有Get访问器
public int Age
{
get{
return age;
}
}
private float h=1.75f;
//只写属性,只有Set访问器
public float H
{
set{
H=value;
}
}
}
public static void Main (string[] args)
{
Person p = new Person ();
// p.SetName ("lanou");
// Console.WriteLine (p.GetName());
p.Name = "lanou";
Console.WriteLine (p.Name);
Console.WriteLine (p.Age);
p.H = 12;
}
}
}