C#、Unity 数据类型的默认值

时间:2023-12-29 14:55:32
using System.Collections;
using System.Collections.Generic;
using UnityEngine; public class Main : MonoBehaviour{
private bool boolVal;
private byte byteVal;
private double doubleVal;
private float floatVal;
private int intVal;
private long longVal;
private short shortVal;
private uint uintVal;
private char charVal;
private string stringVal;
private Vector2 vector2Val;
private Vector3 vector3Val;
private Man classVal;
private CustomData structVal; private bool? boolVal2;
private float? floatVal2;
private int? intVal2;
private System.Nullable<int> intVal3;
private Vector2? vector2Val2;
private Vector2? vector2Val3=null;
private CustomData? structVal2=null; private void Start() {
Debug.LogFormat("boolVal:{0}",boolVal);//output:boolVal:False
Debug.LogFormat("byteVal:{0}",byteVal);//output:byteVal:0
Debug.LogFormat("doubleVal:{0}",doubleVal);//output:doubleVal:0
Debug.LogFormat("floatVal:{0}",floatVal);//output:floatVal:0
Debug.LogFormat("intVal:{0}",intVal);//output:intVal:0
Debug.LogFormat("longVal:{0}",longVal);//output:longVal:0
Debug.LogFormat("{0}",shortVal);//output:shortVal:0
Debug.LogFormat("uintVal:{0}",uintVal);//output:uintVal:0
Debug.LogFormat("charVal:{0},{1}",charVal,charVal=='\0');//output:charVal:
if(charVal=='\0')Debug.Log("True");//output:True
Debug.LogFormat("vector2Val:{0},{1}",vector2Val,vector2Val==Vector2.zero);//output:vector2Val:(0.0, 0.0),True
Debug.LogFormat("vector3Val:{0},{1}",vector3Val,vector3Val==Vector3.zero);//output:vector3Val:(0.0, 0.0, 0.0),True
Debug.LogFormat("classVal:{0},{1}",classVal,classVal==null);//output:classVal:,True
Debug.LogFormat("structVal:{0}",structVal);//output:structVal:CustomData Debug.LogFormat("boolVal2:{0}",boolVal2==null);//output:boolVal2:True
Debug.LogFormat("floatVal2:{0}",floatVal2==null);//output:floatVal2:True
Debug.LogFormat("intVal2:{0}",intVal2==null);//output:intVal2:True
Debug.LogFormat("intVal3:{0}",intVal3==null);//output:intVal3:True
Debug.LogFormat("vector2Val2:{0}",vector2Val2==null);//output:vector2Val2:True
Debug.LogFormat("vector2Val3:{0}",vector2Val3==null);//output:vector2Val3:True
Debug.LogFormat("structVal2:{0}",structVal2==null);//output:structVal2:True
}
} public class Man{ }
public struct CustomData{
public int ID;
}

//更多C#数据类型参考: https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/reference-tables-for-types

//默认值表:https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/default-values-table