今天的主题是枚举,它是C#语言中的一个很有帮助的工具,可以增强代码的清晰度以及准确性。
枚举一系列值
C#中最经常使用枚举的地方就是用来定义一系列可能值的时候。例如在制作一个角色类游戏中,角色有多个不同的状态效果。可以用一些基本的方式来定义玩家可能的状态效果:
using UnityEngine;
public class Player : MonoBehaviour
{
public string status;
void Update()
{
if (status == "Poison")
{
//Apply poison effect
}
else if (status == "Slow")
{
//Apply slow effect
}
else if (status == "Mute")
{
//Apply mute effect
}
}
}
此处我们用一个简单的if-else检测来查看应用的是哪个状态效果,哪个运行良好。但是如果你想应用一个状态效果,但是突然写成这样:
1
2
//Oops, I spelled "Poison" wrong!
status = "Pioson"; unity3d
突然,就不会有什么状态效果了。我们会利用if-else栈检测来查看我们的变量是否被设置成一个非法值,但是如果使用枚举,则是一种更好的方式:
定义一个枚举
这次我们使用一个枚举来编写我们的状态效果:
using UnityEngine;
public class Player : MonoBehaviour
{
//This is the "set" of all possible status effects
public enum StatusEffect
{
None,
Poison,
Slow,
Mute
}
//Now we can make a variable using that set as its type!
public StatusEffect status;
void Update()
{
if (status == StatusEffect.Poison)
{
//Apply poison effect
}
else if (status == StatusEffect.Slow)
{
//Apply slow effect
}
else if (status == StatusEffect.Mute)
{
//Apply mute effect
}
}
}
这里我们定义了一个叫StatusEffect的枚举,通过给状态赋值,我们强制编译器只等于StatusEffect中的一个值,如果还像之前赋值:
//This type doesn't even exist, ERROR TIME!
status = StatusEffect.Pioson;
枚举一系列值
C#中最经常使用枚举的地方就是用来定义一系列可能值的时候。例如在制作一个角色类游戏中,角色有多个不同的状态效果。可以用一些基本的方式来定义玩家可能的状态效果:
using UnityEngine;
public class Player : MonoBehaviour
{
public string status;
void Update()
{
if (status == "Poison")
{
//Apply poison effect
}
else if (status == "Slow")
{
//Apply slow effect
}
else if (status == "Mute")
{
//Apply mute effect
}
}
}
此处我们用一个简单的if-else检测来查看应用的是哪个状态效果,哪个运行良好。但是如果你想应用一个状态效果,但是突然写成这样:
1
2
//Oops, I spelled "Poison" wrong!
status = "Pioson"; unity3d
突然,就不会有什么状态效果了。我们会利用if-else栈检测来查看我们的变量是否被设置成一个非法值,但是如果使用枚举,则是一种更好的方式:
定义一个枚举
这次我们使用一个枚举来编写我们的状态效果:
using UnityEngine;
public class Player : MonoBehaviour
{
//This is the "set" of all possible status effects
public enum StatusEffect
{
None,
Poison,
Slow,
Mute
}
//Now we can make a variable using that set as its type!
public StatusEffect status;
void Update()
{
if (status == StatusEffect.Poison)
{
//Apply poison effect
}
else if (status == StatusEffect.Slow)
{
//Apply slow effect
}
else if (status == StatusEffect.Mute)
{
//Apply mute effect
}
}
}
这里我们定义了一个叫StatusEffect的枚举,通过给状态赋值,我们强制编译器只等于StatusEffect中的一个值,如果还像之前赋值:
//This type doesn't even exist, ERROR TIME!
status = StatusEffect.Pioson;