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

后端 未结 12 900
庸人自扰
庸人自扰 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());
            }
        }
    }
    

提交回复
热议问题