語法糖(syntactic sugar)是由英國計算機科學家Peter J. Landin發明的術語,指計算機語言中添加的某種語法。這種語法不影響語言的功能,但更方便使用。
在開發中使用語法糖能夠讓程序變得更短,使看起來更美觀些~
空檢查
public event System.Action onClick;
?
public void Click(){ onClick?.Invoke(); //等價于//if(onClick != null)// onClick.Invoke();
}
自動屬性
public int value { get; private set; } = 1;
?
//等價于
//private int _number = 1;
//public int Number{
// get{ return _number; }
// private set{ _number = value; }
//}
組件懶加載
private Rigidbody2D _r2d;
public Rigidbody2D r2d => _r2d ??= GetComponent<Rigidbody2D>();
?
//等價于
//public Rigidbody2D r2d{
// get{
// if(_r2d == null)
// _r2d = GetComponent<Rigidbody2D>();
// return _r2d;
// }
//}
匿名函數
[SerializeField] string[] array;
?
private void Start(){System.Array.ForEach(array, (x) => Debug.Log(x));//等價于//for (int i = 0; i < array.Length; i++){// Debug.Log(array[i]);//}
}
動態變量
public object obj;
?
dynamic obj_d = obj;
int result = obj_d.Add(1, 2);
?
//等價于
//Type t = obj.GetType();
//MethodInfo mi = t.GetMethod("Add");
//int result = (int)mi.Invoke(obj, new object[] { 1, 2 });