Greyed out my codes of null checking before invoking a delegate

我怕爱的太早我们不能终老 提交于 2019-12-02 11:04:25

问题


I write unity codes in VS 2015, which means it's in c#4 and the null condition operator is not available.

Before invoking a delegate, I did a null check. However the codes are greyed out. Does it mean the grey codes are not effective just like comments? If so what should I do to prevent invoking a null delegate?

public delegate void PtjAnimCtrlDelegateColiderSetEnabledTo(bool value);
public PjtAnimCtrlDelegateColliderSetEnabledTo colliderSetEnabledToHandler;

public delegate void PjtAnimCtrlDelegate();
public PjtAnimCtrlDelegate explosionAnimationFinishedHandler;
public PjtAnimCtrlDelegate hitTargetHandler;

public void ExplosionAnimationFinished()
{
  //pjtCtrl.ExplosionAnimationFinished();
  explosionAnimationFinishedHandler();
}

public void SetColliderEnabled()
{
  colliderSEtEnabledToHandler(true);
}

public void SetColliderDisabled() 
{
  colliderSetEnabledToHandler(false);
}

public void HitTarget()
{
  // this IF statement is gray in Visual Studio
  if (hitTargetHandler != null)
  { 
    hitTargetHandler();
  }
}

回答1:


Before invoking a delegate, I did a null check. However the codes are greyed out. Does it mean the grey codes are not effective just like comments?

It means that the Visual Studio pre-compiler/design-time-compiler detects the statement is most likely not needed.

If so what should I do to prevent invoking a null delegate?

Nothing, the compiler will still determine at compile time (and actually at run-time as well) if the statement is needed.




回答2:


I've just heard that grey codes in VS will still be compiled. The null check is still effective. So this is not a problem at all.

IDE makes it grey to suggest that there's simpler formats, which is the null condition operator in my case. However it should not give such suggestion here, just ignore it would be fine.



来源:https://stackoverflow.com/questions/38559048/greyed-out-my-codes-of-null-checking-before-invoking-a-delegate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!