Statements cannot exist outside of methods?
Reading a book (VS 2010), it says that commands (statements) in .NET Csharp cannot exist outside of method. I am wondering - field declaration etc, these are commands, a开发者_JS百科re they not? And they exist at class level. Can somebody elaborate at this a bit?
If you mean:
class Foo
{
int count = 0;
StringBuilder buffer = new StringBuilder();
}
The count and buffer are declarations using initializer expressions . But this code contains no statements.
A field initialiser is written with the code outside a method, but the compiler puts that code inside the constructor.
So a field initialiser like this:
class Foo {
int Bar = 42;
}
is basiclally a field and an initialiser in the constructor:
class Foo {
int Bar;
Foo() {
Bar = 42;
}
}
There's no such concept as a "command" in C#.
And a static / instance variable declaration isn't categorized as a statement within C# - it's a field-declaration (which is a type of class-member-declaration) as per the C# spec. See section 10.5 of the C# 4 spec for example.
Now the statements which declare local variables are statements, as defined by declaration-statement in the spec (section 8.5). They're only used for locals though. See section B.2.5 for a complete list of statement productions within C# 4.
Basically, the C# spec defines the terminology involved - so while you might think informally of "commands" and the like, in a matter of correctness the C# spec is the source of authority. (Except for where it doesn't say what the language designers meant to say, of course. That's pretty rare.)
As you said they're declarations, a statement is one which actually gets something done.
No, they're declarations. Class member declarations, to be precise.
And it's perfectly legal for those to exist outside of a method. Otherwise, you couldn't declare a method in the first place!
By "statements", the book is telling you that you can't have things like method calls outside of a method. For example, the following code is illegal:
public void DoSomething()
{
// Do something here...
}
MessageBox.Show("This statement is not allowed because it is outside a method.");
Classes, namespace, fields declarations are not declarations statements.
A field can be initialised outside a method with an expression but while an expression is a statement there are lots of statements that are not expressions (eg. if
).
It all comes down to how the language grammar defines the terms, and the way C# does it is pretty common (eg. very similar to C and C++).
精彩评论