You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复PowerShell嵌入C#时System.Runtime的CS1701版本冲突错误

解决PowerShell中Websocket.Client与System.Runtime版本冲突问题

问题根源

Websocket.Client程序集依赖System.Runtime 6.0.0.0,但当前PowerShell环境加载的是System.Runtime 7.0.0.0,同时原C#代码存在语法错误,共同导致编译失败。

修复步骤

1. 修正C#代码中的语法错误

原代码事件定义存在语法问题,将:

public Event EventHandler<ReconnectionInfo> Connection;

改为:

public event EventHandler<ReconnectionInfo> Connection;

(缺少event关键字,这是编译错误的直接原因之一)

2. 移除不必要的程序集引用

删除C#代码中的using System.Runtime;语句,该命名空间的核心类型已被默认引用,显式引用反而会触发版本检查逻辑。

3. 添加程序集绑定重定向逻辑

在PowerShell中注册程序集解析事件,当请求6.0版本的System.Runtime时,自动返回当前环境中的7.0版本:

修改后的完整函数如下:

function New-ClientWebSocketEventBridge {
    param (
        [parameter(Mandatory = $True)]
        [ValidateNotNullOrEmpty()]
        [Websocket.Client.WebsocketClient] $ws
    )

    # 注册程序集绑定重定向,处理System.Runtime版本冲突
    if (-not [System.AppDomain]::CurrentDomain.GetEventHandlers('AssemblyResolve')) {
        $null = [System.AppDomain]::CurrentDomain.add_AssemblyResolve({
            param($sender, $args)
            # 匹配System.Runtime 6.0版本请求,返回当前加载的7.0版本
            if ($args.Name -like 'System.Runtime, Version=6.0.0.0,*') {
                return [System.Runtime.GetType].Assembly
            }
            return $null
        })
    }

    # 检查类型是否已定义
    if (-not ("ClientWebSocketEventBridge" -as [type])) {
        $cp = @"
using System;
using Websocket.Client;
using Websocket.Client.Models;

public sealed class ClientWebSocketEventBridge {
    
    public event EventHandler<ReconnectionInfo> Connection;
    
    public WebsocketClient wsConnection;
    public string Name;
    
    private ClientWebSocketEventBridge(WebsocketClient ws) {
        wsConnection = ws;
        if (ws.Name != null) { Name = ws.Name; }
        ws.ReconnectionHappened.Subscribe(info => Connection?.Invoke(this, info));
    }
    
    public static ClientWebSocketEventBridge Create(WebsocketClient ws)
    {
        return new ClientWebSocketEventBridge(ws);
    }
}
"@
        Add-Type -TypeDefinition $cp -ReferencedAssemblies 'Websocket.Client'
    }

    $bridge = [ClientWebSocketEventBridge]::Create($ws)
    return $bridge
}

4. 修复逻辑说明

  • 程序集解析事件会拦截对System.Runtime 6.0的请求,返回当前PowerShell环境中的7.0版本,绕过版本检查
  • 修正后的C#代码语法正确,移除了冗余引用,避免触发额外的版本冲突检查

内容的提问来源于stack exchange,提问作者Alain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 21:29:57