Язык C# для начинающих
Структура программы C#
Чтобы понять принципы работы программы C#, давайте рассмотрим традиционную программу "Hello World!" и разберем каждую строку ее кода на C#.
"Hello World" в стиле C#
Для упорядочения и оформления кода в языке C# используются классы. В действительности весь выполняемый код C# должен содержаться в классе, что справедливо и для короткой программы типа "Hello World!". Ниже приведен полный текст программы, отображающей в окне консоли сообщение "Hello World!".
using System;
// A Hello World! program in C#
namespace HelloWorld
{
class Hello
{
static void Main()
{
System.Console.WriteLine("Hello World!");
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
}
using Directives and Namespaces
When you create a console application with Visual C#, the first lines in the code editor contain using directives listing several .NET Framework namespaces. A namespace is a way of grouping classes and structs together in a way that limits their scope and avoids name conflicts with other classes and structs. When you create a program in Visual C#, a namespace is automatically created for you. To use classes from other namespaces in your program, you must specify them with a using Directive. The most commonly used.NET Framework namespaces are listed by default when you create a new application. If you use classes from other namespaces in the class library, you must add a using directive for that namespace to the source file.
When the Code Editor detects that you have declared a class or struct that it cannot find in the namespaces listed in the current using directives, it will suggest namespaces that contain the class or struct.
Comments
After the using statements, the next line contains a comment. Comments are useful for including notes to yourself or other programmers.
// A "Hello World!" program in C# |
The characters // convert the rest of the line to a comment. You can also comment a block of text by placing it between the characters /* and */, for example:
/* A "Hello World!" program in C#. This program displays the string "Hello World!" on the screen. */ |
Дата добавления: 2022-05-27; просмотров: 113;