while循环语法解释

时间:2017-12-18 04:45:17

标签: c# while-loop xsd

在研究XSD验证时正在阅读this。碰到了这段代码。

private static IEnumerable<ValidationEventArgs> RunValidation(string inputXml, bool includeHelperSchema)
{
    var schemaSet = new XmlSchemaSet();
    schemaSet.Add(schemaUnderTest);

    if (includeHelperSchema)
    {
        schemaSet.Add(helperSchema);
    }

    var readerSettings = new XmlReaderSettings()
    {
        Schemas = schemaSet,
        ValidationType = ValidationType.Schema,
        ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings,
    };

    var events = new List<ValidationEventArgs>();
    readerSettings.ValidationEventHandler += (s, e) => { events.Add(e); };

    using (var reader = XmlReader.Create(new StringReader(inputXml), readerSettings))
    {
        while (reader.Read())
            ;
    }

    return events;
}

有人可以向我解释分号放在这里的目的是什么?

while (reader.Read())
        ;

删除会出现错误“Invalid expression term '}' ; expected”。

3 个答案:

答案 0 :(得分:4)

Let's look at documentation, where while keyword defined:

while_statement
    : 'while' '(' boolean_expression ')' embedded_statement
    ;

As you see, while statement must end with ;. So, if embedded_statement is empty, you'll get:

while (boolean_expression)
    ;

instead of:

while (boolean_expression)
    embedded_statement
    ;

embedded_statement can be one line expression like Console.WriteLine() or a block of code in { } braces:

while (boolean_expression)
{
    embedded_statement
}
;

Here, ; is not necessary, you can write simple:

while (boolean_expression)
{
    embedded_statement
}

答案 1 :(得分:0)

Put the body for while loop

    while(reader.Read()){ 
    // your code there
    }

答案 2 :(得分:0)

while (reader.Read());

The semicolon is just causing the while loop to continually evaluate reader.Read() until it returns false

Another way to write this could be

var result = reader.Read()
while (result)
{
   result = reader.Read();
}