Raise an event of a class from a different class in C#

后端 未结 12 891
庸人自扰
庸人自扰 2020-11-28 07:44

I have a class, EventContainer.cs, which contains an event, say:

public event EventHandler AfterSearch;

I have another class, EventRaiser.c

相关标签:
12条回答
  • 2020-11-28 08:14

    It is POSSIBLE, but using clever hack.

    Inspired by http://netpl.blogspot.com/2010/10/is-net-type-safe.html

    If you don't believe, try this code.

    using System;
    using System.Runtime.InteropServices;
    
    namespace Overlapping
    {
        [StructLayout(LayoutKind.Explicit)]
        public class OverlapEvents
        {
            [FieldOffset(0)]
            public Foo Source;
    
            [FieldOffset(0)]
            public OtherFoo Target;
        }
    
        public class Foo
        {
            public event EventHandler Clicked;
    
            public override string ToString()
            {
                return "Hello Foo";
            }
    
            public void Click()
            {
                InvokeClicked(EventArgs.Empty);
            }
    
            private void InvokeClicked(EventArgs e)
            {
                var handler = Clicked;
                if (handler != null)
                    handler(this, e);
            }
        }
    
        public class OtherFoo
        {
            public event EventHandler Clicked;
    
            public override string ToString()
            {
                return "Hello OtherFoo";
            }
    
            public void Click2()
            {
                InvokeClicked(EventArgs.Empty);
            }
    
            private void InvokeClicked(EventArgs e)
            {
                var handler = Clicked;
                if (handler != null)
                    handler(this, e);
            }
    
            public void Clean()
            {
                Clicked = null;
            }
        }
    
        class Test
        {
            public static void Test3()
            {
                var a = new Foo();
                a.Clicked += AClicked;
                a.Click();
                var o = new OverlapEvents { Source = a };
                o.Target.Click2();
                o.Target.Clean();
    
                o.Target.Click2();
                a.Click();
            }
    
            static void AClicked(object sender, EventArgs e)
            {
                Console.WriteLine(sender.ToString());
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-28 08:15

    I stumbled across this problem as well, because i was experimenting with calling PropertyChanged events from outside. So you dont have to implement everything in every class. The solution from halorty wouldn't work using interfaces.

    I found a solution working using heavy reflection. It is surely slow and is breaking the principle that events should only be called from inside a class. But it is interesting to find a generic solution to this problem....

    It works because every event is a list of invocation methods being called. So we can get the invocation list and call every listener attached to that event by our own.

    Here you go....

    class Program
    {
      static void Main(string[] args)
      {
        var instance = new TestPropertyChanged();
        instance.PropertyChanged += PropertyChanged;
    
        instance.RaiseEvent(nameof(INotifyPropertyChanged.PropertyChanged), new PropertyChangedEventArgs("Hi There from anywhere"));
        Console.ReadLine();
      }
    
      private static void PropertyChanged(object sender, PropertyChangedEventArgs e)
      {
        Console.WriteLine(e.PropertyName);
      }
    }
    
    public static class PropertyRaiser
    {
      private static readonly BindingFlags staticFlags = BindingFlags.Instance | BindingFlags.NonPublic;
    
      public static void RaiseEvent(this object instance, string eventName, EventArgs e)
      {
        var type = instance.GetType();
        var eventField = type.GetField(eventName, staticFlags);
        if (eventField == null)
          throw new Exception($"Event with name {eventName} could not be found.");
        var multicastDelegate = eventField.GetValue(instance) as MulticastDelegate;
        if (multicastDelegate == null)
          return;
    
        var invocationList = multicastDelegate.GetInvocationList();
    
        foreach (var invocationMethod in invocationList)
          invocationMethod.DynamicInvoke(new[] {instance, e});
      }
    }
    
    public class TestPropertyChanged : INotifyPropertyChanged
    {
      public event PropertyChangedEventHandler PropertyChanged;
    }
    
    0 讨论(0)
  • 2020-11-28 08:15

    I had a similar confusion and honestly find the answers here to be confusing. Although a couple hinted at solutions that I would later find would work.

    My solution was to hit the books and become more familiar with delegates and event handlers. Although I've used both for many years, I was never intimately familiar with them. http://www.codeproject.com/Articles/20550/C-Event-Implementation-Fundamentals-Best-Practices gives the best explanation of both delegates and event handlers that I've ever read and clearly explains that a class can be a publisher of events and have other classes consume them. This article: http://www.codeproject.com/Articles/12285/Implementing-an-event-which-supports-only-a-single discusses how to single-cast events to only one handler since delegates are multicast by definition . A delegate inherits system.MulticastDelegate most including the system delegates are Multicast. I found that multicast meant that any event handler with the same signature would receive the raised event. Multicast behavior has caused me some sleepless nights as I stepped through code and saw my event seemingly erroneously being sent to handlers that I had no intention of getting this event. Both articles explains this behavior. The second article shows you one way, and the first article shows you another, by making the delegate and the signature tightly typed. I personally believe strong typing prevents stupid bugs that can be a pain to find. So I'd vote for the first article, even though I got the second article code working. I was just curious. :-)

    I also got curious if I could get #2 articles code to behave like how I interpreted the original question above. Regardless of your chosen approach or if I'm also misinterpreting the original question, my real message is that I still think you would benefit from reading the first article as I did, especially if the questions or answers on this page leave you confused. If you are having multicast nightmares and need a quick solution then article 2 may help you.

    I started playing with the second article's eventRaiser class. I made a simple windows form project. I added the second articles class EventRaiser.cs to my project. In the Main form's code, I defined a reference to that EventRaiser class at the top as

    private EventRaiser eventRaiser = new EventRaiser();
    

    I added a method in the main form code that I wanted to be called when the event was fired

    protected void MainResponse( object sender, EventArgs eArgs )
    {            
        MessageBox.Show("got to MainResponse");
    }
    

    then in the main form's constructor I added the event assignment:

    eventRaiser.OnRaiseEvent += new EventHandler(MainResponse);`
    

    I then created a class that would be instantiated by my main form called "SimpleClass" for lack of creative ingenuity at the moment.

    Then I added a button and in the button's click event I instantiated the SimpleClass code I wanted to raise an event from:

        private void button1_Click( object sender, EventArgs e )
       {            
           SimpleClass sc = new SimpleClass(eventRaiser);
       }
    

    Note the instance of "eventRaiser" that I passed to SimpleClass.cs. That was defined and instantiated earlier in the Main form code.

    In the SimpleClass:

    using System.Windows.Forms;
    using SinglecastEvent; // see SingleCastEvent Project for info or http://www.codeproject.com/Articles/12285/Implementing-an-event-which-supports-only-a-single
    
        namespace GenericTest
        {
    
            public class SimpleClass
            {
    
                private EventRaiser eventRaiser = new EventRaiser();
    
                public SimpleClass( EventRaiser ev )
                {
                    eventRaiser = ev;
                    simpleMethod();
    
                }
                private void simpleMethod()
                {
    
                    MessageBox.Show("in FileWatcher.simple() about to raise the event");
                    eventRaiser.RaiseEvent();
                }
            }
        }
    

    The only point to the private method I called SimpleMethod was to verify that a privately scoped method could still raise the event, not that I doubted it, but I like to be positive.

    I ran the project and this resulted in raising the event from the "simpleMethod" of the "SimpleClass" up to the main form and going to the expected correct method called MainResponse proving that one class can indeed raise an event that is consumed by a different class. Yes the event has to be raised from within the class that needs it's change broadcast to other classes that care. Receiving classes can be one class or many many classes depending on how strongly typed you defined them or by making them single cast as in 2nd article.

    Hope this helps and not muddy the water. Personally I've got a lot of delegates and events to clean up! Multicast demons begone!

    0 讨论(0)
  • 2020-11-28 08:17

    This is not possible, Events can only be risen from inside the class. If you could do that, it would defeat the purpose of events (being able to rise status changes from inside the class). I think you are misunderstanding the function of events - an event is defined inside a class and others can subscribe to it by doing

    obj.AfterSearch += handler; (where handler is a method according to the signature of AfterSearch). One is able to subscribe to the event from the outside just fine, but it can only be risen from inside the class defining it.

    0 讨论(0)
  • 2020-11-28 08:18

    Agree with Femaref -- and note this is an important difference between delegates and events (see for example this blog entry for an good discussion of this and other differences).

    Depending on what you want to achieve, you might be better off with a delegate.

    0 讨论(0)
  • 2020-11-28 08:20

    You can write a public method on the class you want the event to fire from and fire the event when it is called. You can then call this method from whatever user of your class.

    Of course, this ruins encapsulation and is bad design.

    0 讨论(0)
提交回复
热议问题