p是一个变量但是像一个类型一样使用

时间:2017-08-09 11:11:22

标签: c# asp.net

我正在使用OpenXML和C#来构建应用程序。我认为这是一个与C#相关的常见错误,而不是其他内容。

我想访问p循环范围之外的foreach,所以我将其指定为全局变量,但是我收到此错误:

  

p是一个变量但是像类型一样使用

Paragraph p = new Paragraph();
foreach (p in myIEnumerable){
    /* Do something with p */
}

5 个答案:

答案 0 :(得分:8)

您收到错误的原因

  

p是一个变量但是像类型一样使用

是因为foreach循环的语法是

for([type] [variable] in [enumerable])

您已使用变量p代替预期的类型(请注意,您可以替换关键字var的类型)

答案 1 :(得分:1)

错误是语法错误。你应该

foreach (var p in doc.MainDocumentPart.Document.Body.Descendants...

然后正如其他人指出的那样,在循环中声明一个名为p的新变量时会遇到问题。

答案 2 :(得分:0)

foreach的正确语法是

foreach(var p in myList){//myList is some collection

}

这就是您收到错误的原因。 foreach关键字后括号内的第一个单词应该是类型(类名或任何其他类型)或var关键字。

所以,在你的情况下,你应该在下面

Paragraph p = null;
foreach(var p1 in myList){
   p = p1;
}

答案 3 :(得分:0)

您要将值附加到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();
 }

答案 4 :(得分:-1)

你需要:

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();