有没有办法知道在VB.NET如果处理程序已注册的事件? [英] Is there a way to know in VB.NET if a handler has been registered for an event?
问题描述
在C#中,我可以测试这个...
In C# I can test for this...
public event EventHandler Trigger;
protected void OnTrigger(EventArgs e)
{
if (Trigger != null)
Trigger(this, e);
}
有没有办法做到这一点在VB.NET?测试空我的意思吗?
Is there a way to do this in VB.NET? Test for null I mean?
更多信息
我忘了提。我已经写在C#类,但我写我的单元测试在VB.NET。
I forgot to mention. I have classes written in C# but I am writing my unit tests in VB.NET.
我想这在单元测试...
I am trying this in the unit test...
If myObject.Trigger IsNot Nothing Then
''#do something
End If
这是造成编译时错误它说......公共事件触发一个事件,不能直接调用。使用RaiseEvent语句引发一个事件。
This is causing a compile time error which says ... "Public Event Trigger is an Event and cannot be called directly. Use the RaiseEvent statement to raise an event."
赛斯
推荐答案
有问题的 1129517 。
由于包含事件类是用C#编写,委托语义仍然适用,而那些技术应该为你工作。但是,你需要转换的源VB.NET的单元测试。
Since the class that contains the Event was written in C#, the delegate semantics do apply, and those techniques should work for you. However, you'll need to translate the source to VB.NET for your unit test.
考虑下面的类在C#程序集:
Given the following class in a C# assembly:
public class Triggerific
{
public event EventHandler Trigger;
private static void OnTriggerTriggered(object sender, EventArgs e)
{
Console.WriteLine("Triggered!");
}
public void AddTrigger()
{
Trigger += OnTriggerTriggered;
}
}
下面是一些VB.NET code,将正确地确定是否处理程序注册了触发事件:
Here is some VB.NET code which will correctly determine if a handler was registered for the Trigger event:
<TestMethod()> _
Public Sub TriggerTest()
Dim cut As New Triggerific
cut.AddTrigger()
Assert.IsNotNull(GetEventHandler(cut, "Trigger"))
End Sub
Private Shared Function GetEventHandler(ByVal classInstance As Object, ByVal eventName As String) As EventHandler
Dim classType As Type = classInstance.[GetType]()
Dim eventField As FieldInfo = classType.GetField(eventName, BindingFlags.GetField Or BindingFlags.NonPublic Or BindingFlags.Instance)
Dim eventDelegate As EventHandler = DirectCast(eventField.GetValue(classInstance), EventHandler)
' eventDelegate will be null/Nothing if no listeners are attached to the event
Return eventDelegate
End Function
这篇关于有没有办法知道在VB.NET如果处理程序已注册的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!