Home
08 结构
Unity
08 结构
姜睿
姜睿
August 23, 2022
1 min

Table Of Contents

01
与类的区别
02
声明
03
创建、赋值、读取
04
初始值 & 构造函数
05
类和结构的选择

与类的区别

  • 类是引用类型,结构体是值类型。
  • 结构体是隐式密封的,所以不具有派生类。

声明

1
2internal struct Name
3{
4public int Field;
5}
6

创建、赋值、读取

1
2using static System.Console;
3
4internal struct Vertice
5{
6public double X;
7public double Y;
8public double Z;
9}
10
11internal class Program
12{
13private static void Main()
14{
15Vertice v = new Vertice();
16v.X = v.Y = v.Z = 1;
17WriteLine($"X: {v.X}");
18// X: 1
19}
20}
21

初始值 & 构造函数

1
2using static System.Console;
3
4// If No Constructor, CS8983
5// A 'struct' with field
6// initializers must include
7// an explicitly declared constructor.
8internal struct Vertice
9{
10public double X = 0;
11public double Y = 0;
12public double Z = 0;
13
14public Vertice(double X, double Y, double Z)
15{
16this.X = X;
17this.Y = Y;
18this.Z = Z;
19}
20}
21
22internal class Program
23{
24private static void Main()
25{
26// Good here ↓
27Vertice v = new Vertice();
28v.X = v.Y = v.Z = 1;
29WriteLine($"X: {v.X}");
30// X: 1
31}
32}
33

不使用 new 关键字

1
2using static System.Console;
3
4internal struct Vertice
5{
6public double X = 0;
7public double Y = 0;
8public double Z = 0;
9
10public Vertice() { }
11}
12
13internal class Program
14{
15private static void Main()
16{
17// Good here ↓
18Vertice v;
19// CS0170
20// Use of possibly
21// unassigned field 'field'
22WriteLine($"X: {v.X}");
23}
24}
25

类和结构的选择 1

  • 类型的实例很小、寿命短。

  1. Choosing Between Class and Struct.

Tags

#game develop
姜睿

姜睿

学生

游戏设计学生

Expertise

游戏开发
平面设计

Related Posts

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

Legal Stuff

Privacy NoticeCookie PolicyTerms Of Use