how to fixed CS0070 error?
Error:
Error CS0070 The event 'Demo.MyEvent' can only appear on the left hand side of = or -= (except when used from within the type 'Demo')
Code:
class Demo
{
public event EventHandler<int> MyEvent;
public void Handler(object sender, int arg)
{
Console.WriteLine($"I just go {arg}");
}
}
class Program
{
static void Main(string[] args)
{
var demo = new Demo();
var eventInfo = typeof(Demo).GetEvent("MyEvent");
var handlerMethod = demo.GetType().GetMethod("Handler");
var handler = Delegate.CreateDelegate(
eventInfo.EventHandlerType,
null,
handlerMethod
);
eventInfo.AddEventHandler(demo, handler);
demo.MyEvent?.Invoke(null, 312);
}
}
Error line:
demo.MyEvent?.Invoke(null, 312);
CodePudding user response:
Field-like events (which this is) act like a field to the declaring type, but just appear like an event add/remove pair to external types. This means that only the type that declares the event can do things like access the current value, which is required in order to invoke the backing delegate. Basically, there's a hidden private field that the compiled declares that you can't see - and when you access the event from within the type, you're talking to the field directly. But when accessing the event from outside, you have to go via the accessors - and the only accessors that C# provides are the add and remove accessors.
If you write a method inside Demo
, that method will be able to invoke the event.
CodePudding user response:
Thanks Mr. Marc Gravell.
Excuse me, My code is wrong.
Correct code is:
namespace ConsoleApp1
{
class Demo
{
public event EventHandler<int> MyEvent;
public void Handler(object sender, int arg)
{
Console.WriteLine($"I just go {arg}");
}
public static void Main(string[] args)
{
var demo = new Demo();
var eventInfo = typeof(Demo).GetEvent("MyEvent");
var handlerMethod = demo.GetType().GetMethod("Handler");
var handler = Delegate.CreateDelegate(
eventInfo.EventHandlerType,
null,
handlerMethod
);
eventInfo.AddEventHandler(demo, handler);
demo.MyEvent?.Invoke(null, 312);
}
}
}
CodePudding user response:
Event must be invoked directly form it's class, if your scenario requires to invoke it from outside the event then simply encapsulate your event with a method like that:
public void InvokeMyEvent(int value)
{
MyEvent?.Invoke(this,value);
}
Then subscribe to it easily with a short code like this;
demo.MyEvent = MyEvent_EventHandeler;
private void My_EventHandeler(object sender, int e)
{
//enter code here
}
Or event shorter with lambda like this:
demo.MyEvent = (s, e) =>
{
//enter code here
}
Invoke it from anywhere:
demo.InvokeMyEvent(321);