Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Prog_Guide.doc
Скачиваний:
16
Добавлен:
16.11.2019
Размер:
6.22 Mб
Скачать

Разбор строк

Метод Parse преобразует строку, представляющую базовый тип .NET Framework, в реальный базовый тип .NET Framework. Поскольку разбор — это операция, обратная форматированию (преобразования базового типа в строковое представление), то применимы многие схожие правила и условия. Подобно тому, как при форматировании используется объект, реализующий интерфейс IFormatProvider для форматирования данных в строку, точно так же и при разборе используется объект, реализующий интерфейс IFormatProvider для преобразования в строковое представление.

Разбор числовых строк

Для всех числовых типов имеется статический метод Parse, который можно использовать для преобразования строкового представления числового типа в реальный числовой тип. Эти методы позволяют разбирать строки, которые были созданы с помощью одного из спецификаторов формата в разделе Строки числовых форматов.

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

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

string MyString = "12345";

int MyInt = int.Parse(MyString);

MyInt++;

Console.WriteLine(MyInt);

// The result is "12346".

The NumberStyles enumeration indicates the permitted format of a string to parse. You can use this enumeration to parse a string that contains a currency symbol, a decimal point, an exponent, parentheses, and so on. For example, in the en-US culture, a string that contains a comma cannot be converted to an integer value using the Parse method if the NumberStyles.AllowThousands enumeration is not passed.

NumberStyles.AllowCurrencySymbol specifies that a number should be parsed as a currency rather than as a decimal. NumberStyles.AllowDecimalPoint indicates that a decimal point is allowed. Valid decimal point characters are determined by the NumberDecimalSeparator or CurrencyDecimalSeparator properties of the current NumberFormatInfo object. NumberStyles.AllowThousands indicates that group separators are allowed. Valid group separator characters are determined by the NumberGroupSeparator or CurrencyGroupSeparator properties of the current NumberFormatInfo object. For a complete table of valid nonnumeric character types, see the NumberStyles enumeration documentation.

The NumberStyles enumeration uses the characters specified by the current culture to aid in the parse. If you do not specify a culture by passing a CultureInfo object set to the culture that corresponds to the string you are parsing, the culture associated with the current thread is used.

The following code example is invalid and will raise an exception. It illustrates the improper way to parse a string containing nonnumeric characters. A new CultureInfo is first created and passed to the Parse method to specify that the en-US culture be used for parsing.

using System.Globalization;

CultureInfo MyCultureInfo = new CultureInfo("en-US");

string MyString = "123,456";

int MyInt = int.Parse(MyString, MyCultureInfo);

Console.WriteLine(MyInt);

// Raises System.Format exception.

Перечисление NumberStyles указывает разрешенный формат разбираемой строки. Это перечисление можно использовать для разбора строки, содержащей знак денежной единицы, разделитель целой и дробной частей числа, степень, скобки и т. д. Например, в региональных параметрах en-US строка, содержащая запятую, не может быть преобразована в целое число с использованием метода Parse, если не будет передано перечисление NumberStyles.AllowThousands.

NumberStyles.AllowCurrencySymbol указывает, что число должно разбираться как денежная единица, а не как десятичное число. NumberStyles.AllowDecimalPoint показывает, что разрешен десятичный разделитель. Допустимые знаки десятичного разделителя определены свойствами NumberDecimalSeparator или CurrencyDecimalSeparator текущего объекта NumberFormatInfo. NumberStyles.AllowThousands показывает, что разрешен разделитель групп разрядов. Допустимые знаки разделителей групп разрядов определены свойствами NumberGroupSeparator или CurrencyGroupSeparator текущего объекта NumberFormatInfo. Полную таблицу допустимых типов нечисловых знаков см. в документации на перечисление NumberStyles.

В перечислении NumberStyles используются знаки, описанные в текущих региональных параметрах. Это перечисление используется при разборе. Если региональные параметры не описаны путем передачи объекта CultureInfo, устанавливающего параметры, соответствующие разбираемой строке, то используются региональные параметры, связанные с текущим потоком.

Следующий пример кода является недопустимым и поэтому будет создавать исключение. Этот пример описывает неправильный способ разбора строки, содержащей нечисловые знаки. Сначала создается объект CultureInfo, передаваемый в метод Parse, чтобы указать, что для разбора будут использованы региональные параметры en-US.

-------------

When you apply the NumberStyles enumeration with the AllowThousands flag, the Parse method ignores the comma that raised the exception in the previous example. The following code example uses the same string as the previous example, but does not raise an exception. Similar to the previous example, a new CultureInfo is first created and passed to the Parse method to specify that the thousand separator used by the en-US culture is used for parsing.

using System.Globalization;

CultureInfo MyCultureInfo = new CultureInfo("en-US");

string MyString = "123,456";

int MyInt = int.Parse(MyString, NumberStyles.AllowThousands, MyCultureInfo);

Console.WriteLine(MyInt);

// The result is "123456".

При использовании перечисления NumberStyles с флагом AllowThousands метод Parse не обрабатывает запятую, которая приводила к созданию исключения в предыдущем примере. В следующем примере кода используется та же самая строка, что и в предыдущем, но исключение не создается. Как и в предыдущем примере, сначала создается новый объект CultureInfo, передаваемый в метод Parse для того, чтобы указать, что для разбора будет использован разделитель групп разрядов, применяющийся в региональных параметрах en-US.

using System.Globalization;

CultureInfo MyCultureInfo = new CultureInfo("en-US");

string MyString = "123,456";

int MyInt = int.Parse(MyString, NumberStyles.AllowThousands, MyCultureInfo);

Console.WriteLine(MyInt);

// The result is "123456".

Statements, Expressions, and Operators

This section contains information regarding the fundamental elements that make up a C# program. The C# code that comprises an application consists of statements comprising C# keywords, expressions and operators.

Statements

A statement is a procedural building-block from which all C# programs are constructed. A statement can declare a local variable or constant, call a method, create an object, or assign a value to a variable, property, or field. A control statement can create a loop, such as a for loop, or make a decision and branch to a new block of code, such as an if or switch statement. Statements are usually terminated by a semicolon.

A series of statements surrounded by curly braces form a block of code. A method body is one example of a code block. Code blocks often follow a control statement. Variables or constants declared within a code block are only available to statements within the same code block. For example, the following code shows a method block and a code block following a control statement:

bool IsPositive(int number)

{

if (number > 0)

{

return true;

}

else

{

return false;

}

}

Statements in C# often contain expressions. An expression in C# is a fragment of code containing a literal value, a simple name, or an operator and its operands. Most common expressions, when evaluated, yield a literal value, a variable, or an object property or object indexer access. Whenever a variable, object property or object indexer access is identified from an expression, the value of that item is used as the value of the expression. In C#, an expression can be placed anywhere that a value or object is required as long as the expression ultimately evaluates to the required type.

Some expressions evaluate to a namespace, a type, a method group, or an event access. These special-purpose expressions are only valid at certain times, usually as part of a larger expression, and will result in a compiler error when used improperly.