Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从范围集合填充Word文档_C#_.net_Ms Word_Vsto_Office Addins - Fatal编程技术网

C# 从范围集合填充Word文档

C# 从范围集合填充Word文档,c#,.net,ms-word,vsto,office-addins,C#,.net,Ms Word,Vsto,Office Addins,在我的Word addin中,我有一个来自文档的范围副本列表。Word集合如下: private void button1_Click(object sender, RibbonControlEventArgs e) { Document doc = Globals.ThisAddIn.Application.ActiveDocument; List<Range> list = new List<Range>(); foreach (Range w

在我的Word addin中,我有一个来自文档的范围副本列表。Word集合如下:

private void button1_Click(object sender, RibbonControlEventArgs e)
{
    Document doc = Globals.ThisAddIn.Application.ActiveDocument;
    List<Range> list = new List<Range>();
    foreach (Range word in doc.Words)
    { 
        list.Add(word);
    }
    MessageBox.Show("list: " + list[0].Text + "|"+ list[1].Text + "|"+ list[2].Text + "|"+      list[3].Text + "|"+ list[4].Text);

    list[0].Text = "Hello ";
    MessageBox.Show("list: " + list[0].Text + "|"+ list[1].Text + "|"+ list[2].Text + "|"+ list[3].Text + "|"+ list[4].Text);
}
private void按钮1\u单击(对象发送者,RibbonControlEventArgs e)
{
Document doc=Globals.ThisAddIn.Application.ActiveDocument;
列表=新列表();
foreach(文档字中的范围字)
{ 
列表。添加(word);
}
MessageBox.Show(“列表:+列表[0]。文本+“|”+列表[1]。文本+“|”+列表[2]。文本+“|”+列表[3]。文本+“|”+列表[4]。文本);
列表[0]。Text=“你好”;
MessageBox.Show(“列表:+列表[0]。文本+“|”+列表[1]。文本+“|”+列表[2]。文本+“|”+列表[3]。文本+“|”+列表[4]。文本);
}

现在我创建了一个包含“good”的文档。将列表中的第一项指定给“hello”后,第二项也会更改。该消息显示一个列表,其中包含“你好”、“你好好”(?)、“好”。那么我的代码怎么了?

尝试在列表中添加对范围的引用,而不是其值(文本):

var list=newlist();
foreach(以文档文字表示的范围)
{ 
list.Add(range.Text);
}
或者很快:

var list = new List<string>(doc.Words.Cast<Range>().Select(r => r.Text));
var list=新列表(doc.Words.Cast().Select(r=>r.Text));

因此,现在您可以在不引用VSTO对象的情况下操作字符串。

列表[0]中的
不会有效地执行同样的操作吗?@jeremythonpson:应该肯定。但是OP仍然有一些困难,所以我建议一种解决方法来摆脱VSTO对象(我不确定它们的行为)。谢谢,现在这是正确的。你能解释一下我发布的代码中发生了什么吗?是不是因为我添加了范围对象的引用而错了?@Husky:没有完整的代码很难说。我认为在操作文档、范围及其值等时引用范围有问题。实际上,这就是全部代码。我创建了一个C#word加载项,在其中添加一个功能区,然后在功能区中添加一个按钮。单击该按钮将调用包含代码的函数。我只是将完整的函数添加到问题中
var list = new List<string>(doc.Words.Cast<Range>().Select(r => r.Text));