0

我试图在 cSharp 中引发事件以通知我的应用程序中的代码更改,以便获得 tellDontAsk 场景。

我有从事件类实现的简单类

public class SimpleTellDontAsk : ISomeEvent
{
    public void doSomething(string text, EventHandlerArgs args)
    {
        Console.WriteLine("Email this message {0}", text);
        //sending message with email
        args.IsDo = true;
        RaiseEvent(this, args);
    }

    public event EventHandler RaiseEvent;
}

我定义我的事件类如下

public interface ISomeEvent
{
    event EventHandler RaiseEvent;
}

public class SomeEvent : ISomeEvent
{
    public event EventHandler RaiseEvent;
}

public class EventHandlerArgs : EventArgs
{
    public bool IsDo { get; set; }
}

我尝试将我的代码与 Nunit 测试一起使用

[TestFixture]
public class TestSimpleTellDontAsk
{
    [Test]
    public void Given_Text_When_doSomething_Then_ShouldPubliushArgs()
    {
        var tellDontAsk = new SimpleTellDontAsk();
        var senderEventHandlerArgs = new EventHandlerArgs();
        tellDontAsk.doSomething("test message", senderEventHandlerArgs);
        Assert.IsTrue(senderEventHandlerArgs.IsDo);
    }
}

当我运行测试时,它会出现空引用异常

System.NullReferenceException :对象引用未设置为对象的实例。

我相信缺少某些东西,但无法弄清楚,有什么想法吗?

4

2 回答 2

2

未附加 RaiseEvent

 bool eventFired = false;

 var tellDontAsk = new SimpleTellDontAsk();
 tellDontAsk.RaiseEvent += (o, e) =>
            {
                if (e.IsDo)
                    eventFired = true;
            };
 tellDontAsk.doSomething("test message");
 Assert.IsTrue(eventFired);

此外,如果您想使用自己的 EventArgs“EventHandlerArgs”,您应该选择通用 EventHandler。

eventargs 不应该在方法的参数中提供,它们应该在我们需要引发事件时创建。

public class SimpleTellDontAsk : ISomeEvent
{
    public void doSomething(string text)
    {
        Console.WriteLine("Email this message {0}", text);
        //sending message with email
        if (RaiseEvent != null) //Check if we have listeners
        {
            EventHandlerArgs args = new EventHandlerArgs();
            args.IsDo = true;
            RaiseEvent(this, args);
        }
    }
    public event EventHandler<EventHandlerArgs> RaiseEvent;
}
于 2013-02-27T11:16:54.593 回答
1

RaiseEvent没有附加handler,修改了附加默认handler的代码,我还是不清楚它是如何实现的,告诉不问原则,你只是检查IsDo属性,ISomeEvent有什么用?

public interface ISomeEvent
{
    event Action<ISomeEvent, EventHandlerArgs> RaiseEvent;
}

public class SomeEvent : ISomeEvent
{
    public event Action<ISomeEvent, EventHandlerArgs> RaiseEvent;
}
public class EventHandlerArgs : EventArgs
{
    public bool IsDo { get; set; }
}

public class SimpleTellDontAsk : ISomeEvent
{
    public SimpleTellDontAsk()
    {
        RaiseEvent = (s,e) => { };
    }                                
    public void doSomething(string text, EventHandlerArgs args)
    {
        Console.WriteLine("Email this message {0}", text);
        //sending message with email
        args.IsDo = true;
        RaiseEvent(this, args);
    }

    public event Action<ISomeEvent, EventHandlerArgs> RaiseEvent;
}
于 2013-02-27T11:13:40.530 回答