C#中的Reg事件 [英] Reg Events in c#

查看:131
本文介绍了C#中的Reg事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A,B,C(消费类)共3类.

There are 3 classes A, B, C(Consumer). 

A类调用B引发事件,以便C类可以收到已订阅的消息.如何实现此功能?

Class A calls B to fire event so that Class C can receive as it has subscribed. How to achieve this functionality?

 下面是代码.

 Below is the code.

公共委托无效TestDelegate();
    B类公共课
    {
       公共事件TestDelegate TestEvent;

       公共B(​​)
        {

        }


       公共无效Fire()
        {
            TestEvent();//空引用异常,因为T尚未订阅事件 estEvent始终为空
        }
    }

public delegate void TestDelegate();
    public class B
    {
        public event TestDelegate TestEvent;

        public B()
        {

        }


        public void Fire()
        {
            TestEvent();//Null reference exception as not subscribed to the event as TestEvent is always null
        }
    }

公共A类

{

静态void Main()

static void Main()

{

B b =新的B();

B b = new B();

b.Fire(); //空引用异常,因为未订阅该事件.

b.Fire(); //Null reference exception as not subscribed to the event.

}

}

//消费类应用

公共C类

{

static void Main()

static void Main()

{

B b =新的B();

B b = new B();

b.TestEvent + =新的TestDelegate(c_TestEvent);

b.TestEvent+= new TestDelegate(c_TestEvent);

}

&static void c_TestEvent()
        {
            Console.WriteLine("Console 2 Fired");
        }

 static void c_TestEvent()
        {
            Console.WriteLine("Console 2 Fired");
        }

}


Harish

推荐答案

几件事.

您似乎有两个静态的Main方法.这是不可能的,我猜测启动时只会调用A.Main().因此,不会调用C.Main(),因此不会分配TestEvent.

You appear to have two static Main methods. This is not possible and I'm guessing that only A.Main() is getting called on start up. Hence C.Main() is not getting called and so TestEvent is not getting assigned.

第二,无论如何,始终应测试事件是否为null(请参见此处)  有关事件的教程).

Second, events should always be tested for null anyway (see here for tutorial on events).

public void Fire()
{
   if (TestEvent!=null)
        TestEvent();
 }


这篇关于C#中的Reg事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆