我几个小时都在苦苦挣扎。希望你们中的一些vb.net大师可以帮助恢复我的理智。
场景:我有一个对象(mqtt_client),它暴露了我需要陷阱和处理的连接/断开事件。我需要在我的代码中从多个子/函数/模块访问该对象。所以我在封闭的类中声明它是公共的,但在代码块之外。
如果我在主要子组之外声明它:
Public mqtt_client = New MqttFactory().CreateManagedMqttClient
Public Sub Ruptela_Server(sender As Object, e As EventArgs) Handles MyBase.Load
' Add Event Handlers for Connected and disconnected events
AddHandler mqtt_client.Disconnected, AddressOf MQTTclient_disconnected_handler
AddHandler mqtt_client.Connected, AddressOf MQTTclient_connected_handler
addhandler失败,因为事件没有被mqtt_client公开,我不知道为什么。
但是,如果我这样做:
Public Sub Ruptela_Server(sender As Object, e As EventArgs) Handles MyBase.Load
Dim mqtt_client = New MqttFactory().CreateManagedMqttClient
' Add Event Handlers for Connected and disconnected events
AddHandler mqtt_client.Disconnected, AddressOf MQTTclient_disconnected_handler
AddHandler mqtt_client.Connected, AddressOf MQTTclient_connected_handler
然后addhandler挂钩很好,但是对象只有sub中的范围,不能从不同的模块访问。
我无法将所有这些代码放在封闭块之外,因为addhandler是一种方法,并且不会在那里工作。
我该怎么办呢?我们将非常感激地收到任何指导。
答案 0 :(得分:0)
类型推断仅适用于局部变量,因此虽然这会为mqtt_client
提供.CreateManagedMqttClient
类型Option Infer On
:
Public Sub Ruptela_Server(sender As Object, e As EventArgs) Handles MyBase.Load
Dim mqtt_client = New MqttFactory().CreateManagedMqttClient
这给它类型Object
:
Public mqtt_client = New MqttFactory().CreateManagedMqttClient
Public Sub Ruptela_Server(sender As Object, e As EventArgs) Handles MyBase.Load
为包含As
和enable Option Explicit
at the project level的字段指定显式类型,以避免将来出现问题。 (Option Explicit
和Option Strict
应始终为所有来源启用。)
答案 1 :(得分:0)
@Ryan谢谢。我之前尝试输入mqtt_client AS ManagedClient,之前它失败了,但你的回答让我坚持下去。缺少的部分是我没有钻得足够远,Intellisense没有帮助我:
Public mqtt_client As ManagedClient = New MqttFactory()。CreateManagedMqttClient
而不是
Public mqtt_client As MQTTnet.ManagedClient.ManagedMqttClient = New MqttFactory().CreateManagedMqttClient
感谢关于检查Option Infer的提示。
感谢指针!