在CLR项目中需要将“Embed Interop Types”属性设置为“false”或“true”来解决此问题。
方法1:将“Embed Interop Types”属性设置为“false”
在Visual Studio中,选择你的CLR项目,然后右击选择“属性”,在“常规”选项卡下找到“Embed Interop Types”属性,将其设置为“false”,然后重新生成你的项目。
方法2:将“Embed Interop Types”属性设置为“true”
在Visual Studio中,选择你的CLR项目,然后右击选择“属性”,在“常规”选项卡下找到“Embed Interop Types”属性,将其设置为“true”。这将嵌入对COM组件和其他.NET程序集的相互依赖关系,从而简化部署。你也可以添加以下行到你的项目文件中:
<EmbedInteropTypes>true</EmbedInteropTypes>
这将自动为你的项目设置“Embed Interop Types”属性为“true”。
示例代码:
using System;
using Microsoft.Office.Interop.Word;
namespace MyWordApp
{
class Program
{
static void Main(string[] args)
{
Application wordApp = new Application();
Document wordDoc = wordApp.Documents.Add();
Paragraph para1 = wordDoc.Content.Paragraphs.Add();
para1.Range.Text = "Hello, World!";
wordDoc.SaveAs2(@"C:\Temp\MyWordDoc.docx");
wordDoc.Close();
wordApp.Quit();
}
}
}