这可能听起来像一个愚蠢的问题,我犹豫要发布它,但仍然:如果某些东西只需要在某种条件下运行,哪些更有效:
一个.
if (condition) {
// do
// things...
}
Run Code Online (Sandbox Code Playgroud)
B.
if (!condition) { return; }
// do
// things...
Run Code Online (Sandbox Code Playgroud) 我和一位同事对以下哪一项更优雅存在争议.我不会说谁是谁,所以它是公正的.哪个更优雅?
public function set hitZone(target:DisplayObject):void
{
if(_hitZone != target)
{
_hitZone.removeEventListener(MouseEvent.ROLL_OVER, onBtOver);
_hitZone.removeEventListener(MouseEvent.ROLL_OUT, onBtOut);
_hitZone.removeEventListener(MouseEvent.MOUSE_DOWN, onBtDown);
_hitZone = target;
_hitZone.addEventListener(MouseEvent.ROLL_OVER, onBtOver, false, 0, true);
_hitZone.addEventListener(MouseEvent.ROLL_OUT, onBtOut, false, 0, true);
_hitZone.addEventListener(MouseEvent.MOUSE_DOWN, onBtDown, false, 0, true);
}
}
Run Code Online (Sandbox Code Playgroud)
...要么...
public function set hitZone(target:DisplayObject):void
{
if(_hitZone == target)return;
_hitZone.removeEventListener(MouseEvent.ROLL_OVER, onBtOver);
_hitZone.removeEventListener(MouseEvent.ROLL_OUT, onBtOut);
_hitZone.removeEventListener(MouseEvent.MOUSE_DOWN, onBtDown);
_hitZone = target;
_hitZone.addEventListener(MouseEvent.ROLL_OVER, onBtOver, false, 0, true);
_hitZone.addEventListener(MouseEvent.ROLL_OUT, onBtOut, false, 0, true);
_hitZone.addEventListener(MouseEvent.MOUSE_DOWN, onBtDown, false, 0, true);
}
Run Code Online (Sandbox Code Playgroud) 在 C# 中,我对停止循环感兴趣Parallel.ForEachAsync(考虑和之间的差异StopBreak);因为Parallel.ForEach我可以执行以下操作:
Parallel.ForEach(items, (item, state) =>
{
if (cancellationToken.IsCancellationRequested)
{
state.Stop();
return;
}
// some process on the item
Process(item);
});
Run Code Online (Sandbox Code Playgroud)
但是,由于我有一个需要异步执行的进程,所以我切换到了Parallel.ForEachAsync. ForEachAsync没有该方法Stop(),我可以按break如下方式循环,但我想知道这是否是打破循环的最有效方法(换句话说,循环在收到取消时需要尽快停止要求)。
await Parallel.ForEachAsync(items, async (item, state) =>
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
// some async process on the item
await ProcessAsync(item);
});
Run Code Online (Sandbox Code Playgroud) c# asynchronous cancellation parallel.foreach parallel.foreachasync