事件仅可出现在+=/-=左侧的错误及基类事件定义咨询
解决「事件只能出现在 += 或 -= 的左侧」错误
Hey there, let's fix that frustrating error you're hitting! The issue here comes down to how C# enforces encapsulation for events declared with the event keyword—let's break it down and fix it step by step.
Why this error pops up
When you declare an event using public event EventHandler<...>, C# puts strict access rules in place:
- External code can only subscribe (
+=) or unsubscribe (-=) to the event - You can't directly invoke the event, assign it to
null, or modify it in any other way from outside the class that declared it
If you tried something likeyourInstance.HighestSeverityLevelChanged(this, args)from outside your base class, or evenHighestSeverityLevelChanged = null, that's exactly what triggers this error.
The standard C# fix: Add a protected trigger method
The industry-standard pattern for handling events in C# is to create a protected virtual method in your base class to handle triggering the event. This keeps control of when the event fires within the class hierarchy, and lets subclasses extend the behavior if needed.
- Add the trigger method to your base class
protected virtual void OnHighestSeverityLevelChanged(HighestSeverityLevelChangedEventArgs e) { // Use the null-conditional operator to safely invoke the event (no NullReferenceException!) HighestSeverityLevelChanged?.Invoke(this, e); }
protectedensures only the base class and its subclasses can call this methodvirtuallets subclasses override it (e.g., to add extra logic before/after firing the event)?.Invokechecks if there are any subscribers before firing the event
- Trigger the event from within your base class
Wherever you need to notify subscribers about the severity level change, create your event args and call the trigger method instead of directly touching the event:
// Example: When you detect a severity level change int newSeverity = 4; int oldSeverity = 2; var eventArgs = new HighestSeverityLevelChangedEventArgs { HighestSeverityLevel = newSeverity, PreviousHighestSeverityLevel = oldSeverity }; // Call the trigger method to fire the event OnHighestSeverityLevelChanged(eventArgs);
- Subscribe to the event from external code (the correct way)
Your external code should still use+=to subscribe, which is totally allowed:
var myBaseClassInstance = new YourBaseClassName(); myBaseClassInstance.HighestSeverityLevelChanged += HandleSeverityLevelChange; // The event handler method private void HandleSeverityLevelChange(object sender, HighestSeverityLevelChangedEventArgs e) { Console.WriteLine($"Severity updated: Old={e.PreviousHighestSeverityLevel}, New={e.HighestSeverityLevel}"); }
Quick recap
- Events declared with
eventare encapsulated: external code can only subscribe/unsubscribe - Use a protected virtual
On[EventName]method in the declaring class to trigger the event - Never try to invoke or modify the event directly from outside its declaring class
内容的提问来源于stack exchange,提问作者Ray
相关产品推荐
相关产品推荐

