C#의 기본 클래스에서 상속된 이벤트 발생
C#에서는 이벤트를 용이하게 하기 위해 기본 클래스에서 이벤트를 상속하는 것이 일반적입니다. 파생 클래스에서 처리. 그러나 이러한 상속된 이벤트를 발생시키려면 컴파일러 오류를 방지하기 위한 구체적인 접근 방식이 필요합니다.
기본 클래스가 다음 이벤트를 정의하는 시나리오를 고려해 보세요.
public class BaseClass { public event EventHandler Loading; public event EventHandler Finished; }
파생 클래스에서 다음을 사용하는 Loading 이벤트:
this.Loading(this, new EventHandler());
결과는 오류:
The event 'BaseClass.Loading' can only appear on the left hand side of += or -= (BaseClass')
이 오류는 다른 클래스 멤버와 달리 이벤트를 파생 클래스에서 직접 호출할 수 없기 때문에 발생합니다. 대신, 기본 클래스에 정의된 특정 메서드를 호출하여 상속된 이벤트를 발생시켜야 합니다. 이를 달성하려면 다음 단계가 필요합니다.
public class BaseClass { public event EventHandler Loading; public event EventHandler Finished; protected virtual void OnLoading(EventArgs e) { EventHandler handler = Loading; if( handler != null ) { handler(this, e); } } protected virtual void OnFinished(EventArgs e) { EventHandler handler = Finished; if( handler != null ) { handler(this, e); } } }
public class DerivedClass : BaseClass { public void DoSomething() { // Raise Loading event OnLoading(EventArgs.Empty); // Raise Finished event OnFinished(EventArgs.Empty); } }
이 접근 방식을 따르면 C#의 파생 클래스에서 상속된 이벤트를 안전하고 효율적으로 발생시킬 수 있습니다.
위 내용은 C# 파생 클래스에서 상속된 이벤트를 올바르게 발생시키려면 어떻게 해야 합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!