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

VSTO Word加载项暴露函数无法被独立C#程序调用

解决独立C#程序调用VSTO Word加载项方法的类型错误问题

问题根源

COMAddIn.Object属性返回的是object类型,C#编译器无法识别该对象实际实现了ITestAddin接口,因此直接调用DoSomething()会触发编译错误。

解决方案

方案1:引用加载项程序集并强转类型

如果独立程序可以访问VSTO加载项的程序集(DLL),直接添加引用后,将addIn.Object强转为ITestAddin接口:

Word._Application oWord = new Word.Application();
Word._Document oDoc = new Word.Document();

object addInName = "WordAddIn";
COMAddIn addIn = oWord.COMAddIns.Item(ref addInName);
// 强转为ITestAddin接口
var testAddIn = addIn.Object as WordAddIn.ITestAddin;
if (testAddIn != null)
{
    bool t = testAddIn.DoSomething();
}

方案2:使用dynamic类型绕过编译检查

如果无法引用加载项程序集,可以使用dynamic类型,让运行时解析方法调用:

Word._Application oWord = new Word.Application();
Word._Document oDoc = new Word.Document();

object addInName = "WordAddIn";
COMAddIn addIn = oWord.COMAddIns.Item(ref addInName);
dynamic addInObject = addIn.Object;
bool t = addInObject.DoSomething();

注意:使用dynamic会失去编译时类型检查,若方法名拼写错误或对象未实现该方法,会在运行时抛出异常。

方案3:通过反射调用方法

另一种无需引用程序集的方式是使用反射调用目标方法:

Word._Application oWord = new Word.Application();
Word._Document oDoc = new Word.Document();

object addInName = "WordAddIn";
COMAddIn addIn = oWord.COMAddIns.Item(ref addInName);
object addInObject = addIn.Object;
// 通过反射获取并调用DoSomething方法
bool t = (bool)addInObject.GetType().InvokeMember(
    "DoSomething",
    System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance,
    null,
    addInObject,
    null);

额外注意事项

  • 确保VSTO加载项已在Word中正确安装并启用,否则COMAddIns.Item会找不到对应的加载项。
  • 加载项的类和接口必须标记[ComVisible(true)],且类需继承StandardOleMarshalObject(你的代码已满足此要求)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 21:04:57