예에서 다음 코드를 찾습니다.
public event EventHandler ThresholdReached;
protected virtual void OnThresholdReached(EventArgs e)
{
EventHandler handler = ThresholdReached;
if (handler != null)
handler(this, e);
}
라인의 이유를 이해하고 싶습니다.
EventHandler handler = ThresholdReached;
이런 식으로 할 수는 없습니다.
public event EventHandler ThresholdReached;
protected virtual void OnThresholdReached(EventArgs e)
{
if (ThresholdReached != null)
ThresholdReached(this, e);
}
어느 쪽이든 장단점이 있습니까?
문제는이 선 사이에
if (ThresholdReached != null)
그리고이 줄
ThresholdReached(this, e);
다른 스레드가 ThresholdReached
이벤트 에서 핸들러를 제거했을 수 있습니다 . 그래서 그것은 될 것이고 null
예외가 던져 질 것입니다.
값을 지역 변수에 저장하면 스레드로부터 안전하게 호출 할 수 있습니다.
C # 6부터 다음과 같이 코드를 줄일 수 있습니다.
ThresholdReached?.Invoke(this, e);
이제 컴파일러는 값을 임시 변수에 저장합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다