有没有办法在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中执行此操作?测试为null我的意思是?
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."
Seth
推荐答案
有一个有趣的讨论 1129517 在C#中如何做这个事情。
There is an interesting discussion in question 1129517 around how to do this very thing in C#.
由于包含事件的类是用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代码,将正确确定如果为Trigger事件注册了一个处理程序:
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屋!