我曾尝试在cSharp中引发事件,以通知我的应用程序中的代码更改,以便告诉DontAsk场景。
我有从事件类
实现的简单类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:未将对象引用设置为对象的实例。
我相信有些东西不见了但是想不通,有什么想法吗?
答案 0 :(得分: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”,您应该选择Generic 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;
}
答案 1 :(得分:1)
RaiseEvent没有附加处理程序,修改了附加默认处理程序的代码,我还不清楚它是如何实现的告诉不要问原理,你只是检查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;
}