为什么转换 lambda 表达式时出现错误 CS1660

问题描述 投票:0回答:1

我需要优化 Powershell 脚本并为其添加功能,以收集和协调来自不同类型的多个来源的信息。 这些脚本是事件驱动的,具有反应性并避免轮询。 其中一些来源是 websocket。

为了简化事情,我想使用“Websocket.Client”模块(https://github.com/Marfusios/websocket-client)。 Powershell 对它的使用非常简单。 它唯一的弱点是它本身不生成事件。

‘Websocket.Client’可以在客户端连接、断开连接或接收消息时运行外部代码。 我想使用此代码来触发事件。

我编写了以下从“Websocket.Client”中的 WebsocketClient 类派生的 WebsocketClientExt 类。

if (-not ("WebsocketClientExt" -as [type])) {
  $cp = @"
using System;
using System.Runtime;
using System.Net;
using System.Net.WebSockets;
using Websocket.Client;
using Websocket.Client.Models;

public class WebsocketClientExt : WebsocketClient {
  
  public event EventHandler<DisconnectionInfo> Disconnection;
  
  public WebsocketClientExt( Uri url ): base(url) { }
  
  public void SubscribeEvents () {
    DisconnectionHappened.Subscribe(info => Disconnection?.Invoke(this, info));
  }
    
}
"@
  Add-Type -TypeDefinition $cp -ReferencedAssemblies @( 'Websocket.Client', 'System.Net.WebSockets', 'System.Net.WebSockets.Client' )
}

我不明白为什么当Powershell执行上述脚本时编译器会生成错误CS1660。

Add-Type:
Line |
  22 |      Add-Type -TypeDefinition $cp -ReferencedAssemblies @( 'Websocket. …
     |      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | (15,41): error CS1660: Impossible de convertir expression lambda en type 'IObserver<DisconnectionInfo>', car il ne s'agit pas d'un type délégué
        DisconnectionHappened.Subscribe(info => Disconnection?.Invoke(this, info));

英语:错误 CS1660:无法将 lambda 表达式转换为“IObserver”类型,因为它不是委托类型 DisconnectionHappened.Subscribe(info => Disconnection?.Invoke(this, info));

据我所知 EventHandler 是一个委托……因此,为什么会出现这个错误?

c# powershell delegates
1个回答
0
投票

非常感谢大家的帮助,每个人都给了我一部分解决方案。

按照@EyesShriveledToRaisins的建议,我发现代码中缺少使用System.Reactive.Linq和使用System.Reactive.Subjects。 System.Reactive 程序集需要处理可观察事件。

© www.soinside.com 2019 - 2024. All rights reserved.