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

VS2015中引用System.Runtime.InteropServices出现CS0246错误

解决CS0246:找不到IShellExtInit和IContextMenu的问题

问题根源

IShellExtInit和IContextMenu是Windows Shell的COM接口,不属于你安装的System.Runtime.InteropServices NuGet包,因此单纯引用该包无法解决类型找不到的问题,需要通过以下步骤修复:


1. 添加正确的接口定义或COM引用

方案一:添加COM引用

右键项目 → 添加 → 引用 → COM,找到Microsoft Shell Controls And Automation(通常为版本1.0),勾选后确定。添加后,代码中会自动引入对应的命名空间,即可识别两个接口。

方案二:手动定义接口

如果不想依赖COM引用,可以在代码中手动定义这两个COM接口(需匹配官方Guid和接口结构),修改后的代码如下:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace ExplorerExtension
{
    // 手动定义IShellExtInit接口
    [ComImport]
    [Guid("000214E8-0000-0000-C000-000000000046")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IShellExtInit
    {
        void Initialize(IntPtr pidlFolder, IntPtr pDataObj, IntPtr hKeyProgID);
    }

    // 手动定义IContextMenu接口
    [ComImport]
    [Guid("000214E4-0000-0000-C000-000000000046")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IContextMenu
    {
        void QueryContextMenu(IntPtr hMenu, uint indexMenu, uint idCmdFirst, uint idCmdLast, uint uFlags);
        void InvokeCommand(IntPtr pici);
        void GetCommandString(uint idCmd, uint uType, uint pReserved, StringBuilder pszName, uint cchMax);
    }

    [ComVisible(true)]
    [Guid("257F2702-F2F4-4549-BE83-EA74F2BDC160")]
    public class MyExplorerExtension : IShellExtInit, IContextMenu
    {
        // Implement IShellExtInit
        public void Initialize(IntPtr pidlFolder, IntPtr pDataObj, IntPtr hKeyProgID)
        {
            // Initialization code here
        }

        // Implement IContextMenu
        public void QueryContextMenu(IntPtr hMenu, uint indexMenu, uint idCmdFirst, uint idCmdLast, uint uFlags)
        {
            // Add custom menu items here
        }

        public void InvokeCommand(IntPtr pici)
        {
            // Handle menu item click here
        }

        public void GetCommandString(uint idCmd, uint uType, uint pReserved, StringBuilder pszName, uint cchMax)
        {
            // Provide help text for menu items here
        }
    }
}

2. 修正项目配置不一致问题

  • 统一目标框架:从Packages.config看,项目同时引用了针对.NET 4.8和4.7.1的包,右键项目 → 属性 → 应用程序,将目标框架统一设置为.NET Framework 4.7.1或4.8。
  • 修复绑定重定向版本冲突:App.config中System.Runtime的绑定重定向版本为4.1.1.0,但实际安装的包版本是4.3.0,修改重定向配置匹配实际版本:
<dependentAssembly>
  <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
  <bindingRedirect oldVersion="0.0.0.0-4.3.0" newVersion="4.3.0"/>
</dependentAssembly>

3. 清理并重新生成项目

执行菜单 → 生成 → 清理解决方案,然后执行重新生成解决方案,确保所有引用和配置生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 19:37:11