局部函数和委托
1》局部函数存于堆栈,委托存于堆
2》局部函数在IL只是单纯调用,Lambda会被转成委托和类
3》局部函数在IL中用call调用,不需要校验实例是否存在,而委托在IL中用callvert调用,是需要校验是否有实例存在
4》使用迭代器时,异常的不会立即返回,而局部函数则会
例如:
1、这个在if (lstOrderDetails == null) throw new ArgumentNullException();不会返回异常,只会在foreach (var order in lstOrderDetails)触发异常
private static IEnumerable<string> GetItemSellingPice(List<OrderDetails> lstOrderDetails)
{
if (lstOrderDetails == null) throw new ArgumentNullException();
foreach (var order in lstOrderDetails)
{
yield return ($"Item Name:{order.ItemName}, Selling Price:{order.SellingPrice}");
}
}
2、这个则会在if (lstOrderDetails == null) throw new ArgumentNullException();触发异常
private static IEnumerable<string> GetItemSellingPice(List<OrderDetails> lstOrderDetails)
{
if (lstOrderDetails == null) throw new ArgumentNullException();
return GetItemPrice();
IEnumerable<string> GetItemPrice()
{
foreach (var order in lstOrderDetails)
{
yield return ($"Item Name:{order.ItemName}, Selling Price:{order.SellingPrice}");
}
}
}