General Structure of a C# Program 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

General Structure of a C# Program



C# programs can consist of one or more files. Each file can contain zero or more namespaces. A namespace can contain types such as classes, structs, interfaces, enumerations, and delegates, in addition to other namespaces. The following is the skeleton of a C# program that contains all of these elements.

// A skeleton of a C# program using System; namespace YourNamespace { class YourClass { }   struct YourStruct { }   interface IYourInterface { }   delegate int YourDelegate();   enum YourEnum { }   namespace YourNestedNamespace { struct YourStruct { } }   class YourMainClass { static void Main(string[] args) { //Your program starts here... } } }

Общая структура программы на C#

Программа на языке C# может состоять из одного или нескольких файлов. Каждый файл может содержать ноль или более пространств имен. Пространство имен может включать такие элементы, как классы, структуры, интерфейсы, перечисления и делегаты, а также другие пространства имен. Ниже приведена скелетная структура программы C#, содержащая все указанные элементы.

ß--


Main() and Command Line Arguments

The Main method is the entry point of your program, where you create objects and invoke other methods. There can only be one entry point in a C# program.

class TestClass { static void Main(string[] args) { // Display the number of command line arguments: System.Console.WriteLine(args.Length); } }

Overview

· The Main method is the entry point of your program, where the program control starts and ends.

· It is declared inside a class or struct. It must be static and it should not be public. (In the example above it receives the default access of private.)

· It can either have a void or int return type.

· The Main method can be declared with or without parameters.

· Parameters can be read as zero-indexed command line arguments.

· Unlike C and C++, the name of the program is not treated as the first command line argument.

 


Main() и аргументы командной строки

Метод Main является точкой входа программы, где создаются объекты и вызываются другие методы. В программе C# возможна только одна точка входа.

class TestClass { static void Main(string[] args) { // Display the number of command line arguments: System.Console.WriteLine(args.Length); } }

Общие сведения

· Метод Main является точкой входа программы, в которой начинается и заканчивается управление программой.

· Он объявляется внутри класса или структуры. Он должен быть статическим и не должен быть общим. (В приведенном выше примере он получает доступ по умолчанию типа “закрытый”.)

· Он может иметь возвращаемый тип void или int.

· Метод Main может быть объявлен с параметрами или без них.

· Параметры считываются как аргументы командной строки с нулевым индексированием.

· В отличие от языков C и C++, имя программы не рассматривается в качестве первого аргумента командной строки.

 


Command-Line Arguments

The Main method can use arguments, in which case, it takes one of the following forms:

static int Main(string[] args)
static void Main(string[] args)

The parameter of the Main method is a String array that represents the command-line arguments. Usually you check for the existence of the arguments by testing the Length property, for example:

if (args.Length == 0) { System.Console.WriteLine("Please enter a numeric argument."); return 1; }

You can also convert the string arguments to numeric types by using the Convert class or the Parse method. For example, the following statement converts the string to a long number by using the Parse method on the Int64 class:

long num = Int64.Parse(args[0]);

It is also possible to use the C# type long, which aliases Int64:

long num = long.Parse(args[0]);

You can also use the Convert class method ToInt64 to do the same thing:

long num = Convert.ToInt64(s);

 


Аргументы командной строки

Метод Main может использовать аргументы, принимая в этом случае одну из следующих форм:

static int Main(string[] args)
static void Main(string[] args)

Параметр метода Main является массивом значений типа String, представляющим аргументы командной строки. Обычно наличие аргументов проверяется путем проверки свойства Length, например:

if (args.Length == 0) { System.Console.WriteLine("Please enter a numeric argument."); return 1; }

Кроме того, строковые аргументы можно преобразовать в числовые типы с помощью класса Convert или метода Parse. Например, следующая инструкция преобразует строку в число типа long с помощью метода Parse класса Int64:

long num = Int64.Parse(args[0]);

Также можно использовать тип long языка C#, являющийся псевдонимом типа Int64:

long num = long.Parse(args[0]);

Для выполнения этой операции также можно воспользоваться методом ToInt64 класса Convert:

long num = Convert.ToInt64(s);

 


Example

In this example, the program takes one argument at run time, converts the argument to an integer, and calculates the factorial of the number. If no arguments are supplied, the program issues a message that explains the correct usage of the program.

// arguments: 3
public class Functions { public static long Factorial(int n) { if (n < 0) { return -1; } //error result - undefined if (n > 256) { return -2; } //error result - input is too big   if (n == 0) { return 1; }   // Calculate the factorial iteratively rather than recursively:   long tempResult = 1; for (int i = 1; i <= n; i++) { tempResult *= i; } return tempResult; } }

 

 


Пример

В этом примере программа принимает аргументы по одному и преобразует каждый из них в целое и вычисляет факториал этого числа. Если ни одного аргумента не предоставлено, то программа выдает сообщение, содержащее разъяснение правильного использования данной программы.

ß--------------

 

 


 

class MainClass { static int Main(string[] args) { // Test if input arguments were supplied: if (args.Length == 0) { System.Console.WriteLine("Please enter a numeric argument."); System.Console.WriteLine("Usage: Factorial <num>"); return 1; } try { // Convert the input arguments to numbers: int num = int.Parse(args[0]); System.Console.WriteLine("The Factorial of {0} is {1}.", num, Functions.Factorial(num)); return 0; } catch (System.FormatException) { System.Console.WriteLine("Please enter a numeric argument."); System.Console.WriteLine("Usage: Factorial <num>"); return 1; } } }

Output

The Factorial of 3 is 6.

Comments

The following are two sample runs of the program assuming that the program name is Factorial.exe.

Run #1:

Enter the following command line:

Factorial 10

You get the following result:

The Factorial of 10 is 3628800.

Run #2:

Enter the following command line:

Factorial

You get the following result:

Please enter a numeric argument.

Usage: Factorial <num>

 


Результат

The Factorial of 3 is 6.

Примечания

Ниже приведены два примера выполнения программы, имя файла которой Factorial.exe.

Выполнение №1.

Введите следующую командную строку:

Factorial 10

Результат будет следующим:

The Factorial of 10 is 3628800.

Выполнение №2.

Введите следующую командную строку:

Factorial

Результат будет следующим:

Please enter a numeric argument.

Usage: Factorial <num>

 



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 144; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 3.144.143.31 (0.014 с.)