Home
02 属性
Unity
02 属性
姜睿
姜睿
August 17, 2022
1 min

Table Of Contents

01
声明、定义、赋值、读取
02
属性的特性
03
执行计算
04
只读与只写
05
属性与公有字段

声明、定义、赋值、读取

1
2class Class
3{
4// propType propName {};
5public string? MyProp { get; set; }
6}
7
8class Program
9{
10static void Main()
11{
12Class c = new Class();
13c.MyProp = "Hello Property!";
14Console.WriteLine($"Output: {c.MyProp}"); //Output: Hello Property!
15}
16}
17

属性的特性

  • 与字段不同,属性是成员函数。
  • 不一定为数据存储分配内存。
1// Replace
2internal class Class
3{
4private string myField = "default";
5// Constructor
6public Class(string myField)
7{
8myField = _myField;
9}
10// Methods
11public string GetMyField() { return myField; }
12public void SetMyField(string _myField) { myField = _myField; }
13}
14
15internal class Program
16{
17private static void Main(string[] args)
18{
19Class c = new Class("Hello Field!");
20c.SetMyField("Hello Property!");
21Console.WriteLine($"Output: {c.GetMyField()}");
22}
23}
24
25// With
26internal class Class
27{
28// private field
29private string myField = "default";
30// public prop
31public string MyField { get { return myField; } set { myField = value; } }
32// Constructor
33public Class(string _myField)
34{
35MyField = _myField ;
36}
37}
38
39internal class Program
40{
41private static void Main(string[] args)
42{
43Class c = new Class("Hello Property!");
44c.MyField = "Hello Property!";
45Console.WriteLine($"Output: {c.MyField}");
46}
47}
48

执行计算

  • 属性可以通过执行计算,起到过滤作用。
1
2internal class Player
3{
4private int health = 12;
5public int Health { get => health; set => health = value > 12 ? 12 : value; }
6public Player(int _health = 12) { Health = _health; }
7public void Heal(int _health) { Health += _health; }
8}
9
10internal class Program
11{
12private static void Main(string[] args)
13{
14Player p = new Player();
15p.Heal(-2);
16Console.WriteLine(p.Health); // 10
17p.Heal(4);
18Console.WriteLine(p.Health); // 12
19}
20}
21

只读与只写

只读

1
2internal class RightTriangle
3{
4// a side across from a given angle
5public double Adjacent { get; private set; }
6// the non-hypotenuse side that is next to a given angle
7public double Opposite { get; private set; }
8// the longest side
9public double Hypotenuse
10{
11get
12{
13return Math.Sqrt(Adjacent * Adjacent + Opposite * Opposite);
14}
15}
16public RightTriangle(double adjacent = 3, double opposite = 4)
17{
18Adjacent = adjacent;
19Opposite = opposite;
20}
21}
22
23internal class Program
24{
25private static void Main(string[] args)
26{
27RightTriangle rightTriangle = new RightTriangle();
28Console.WriteLine(rightTriangle.Hypotenuse); // 5
29}
30}
31

属性与公有字段

  • 公有字段无法处理输入和输出。
  • 属性可以只读/只写,而公有字段不行。

Tags

#game developc#
姜睿

姜睿

学生

游戏设计学生

Expertise

游戏开发
平面设计

Related Posts

策略模式
策略模式
November 19, 2023
1 min

Legal Stuff

Privacy NoticeCookie PolicyTerms Of Use