我正在使用OpenXML和C#来构建应用程序。我认为这是一个常见的错误,与 C# 更相关,而不是与其他东西有关。
我想访问foreach
循环范围之外的p
,所以我将其分配为全局变量,但出现此错误:
p 是一个变量,但像类型一样使用
Paragraph p = new Paragraph();
foreach (p in myIEnumerable){
/* Do something with p */
}
您收到错误的原因
p 是一个变量,但像类型一样使用
是因为foreach
循环的语法是
for([type] [variable] in [enumerable])
您已使用变量p
代替预期的 Type(请注意,您可以将类型替换为关键字var
(
该错误是语法错误。 你应该有
foreach (var p in doc.MainDocumentPart.Document.Body.Descendants...
然后,正如其他人指出的那样,在循环中声明一个名为p
的新变量时会遇到问题。
foreach 的正确语法是
foreach(var p in myList){//myList is some collection
}
这就是您收到错误的原因。foreach 关键字后面括号内的第一个单词应该是类型(类名或任何其他类型(或 var 关键字。
因此,在您的情况下,您应该执行以下操作
Paragraph p = null;
foreach(var p1 in myList){
p = p1;
}
您将值附加到P
而是将其附加到列表中
List<Paragraph> pList = new List<Paragraph>();
Paragraph p = new Paragraph();
foreach (p in doc.MainDocumentPart.Document.Body.Descendants<Paragraph().Where<Paragraph>(p => p.InnerText.Equals("The contents of this...")))
{
pList.Append(new Run(new Break() { Type = BreakValues.Page }));
pList.ElementsAfter();
}
我更喜欢这个:
var Par = doc.MainDocumentPart.Document.Body.Descendants<Paragraph().Where<Paragraph>(p => p.InnerText.Equals("The contents of this..."));
foreach (p in Par)
{
pList.Append(new Run(new Break() { Type = BreakValues.Page }));
pList.ElementsAfter();
}
你需要:
foreach (Paragraph p in doc.MainDocumentPart.Document.Body.Descendants<Paragraph>().Where<Paragraph>(p => p.InnerText.Equals("")))
{
/*body*/
}
如果您需要在foreach之后的最后一p
,您可以致电:
Paragraph p = doc.MainDocumentPart.Document.Body.Descendants<Paragraph>().Where<Paragraph>(p => p.InnerText.Equals(""))).Last();
并避免重复代码:
IEnumerable i = doc.MainDocumentPart.Document.Body.Descendants<Paragraph>().Where<Paragraph>(p => p.InnerText.Equals("")));
foreach(Paragraph p in i)
/*body*/
Paragraph p = i.Last();