Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / MS Press - Msdn Training Programming Net Framework With C#

.pdf
Скачиваний:
173
Добавлен:
12.02.2016
Размер:
16.87 Mб
Скачать

Module 7: Strings, Arrays, and Collections

19

 

 

 

Regular Expressions

Topic Objective

To briefly describe how regular expressions can be used in the .NET Framework.

Lead-in

Regular expressions allow you to quickly parse large amounts of text in order to find specific character patterns; to extract, edit, replace, or delete text substrings; and to add the extracted strings to a collection to generate a report.

!Regular Expressions – Powerful Text Processing

!Pattern-Matching Notation Allows You to:

#Find specific character patterns

#Extract, edit, replace, or delete text substrings

#Add the extracted strings to a collection to generate a report

!Designed to be Compatible With Perl 5

*****************************ILLEGAL FOR NON-TRAINER USE******************************

This topic provides a brief summary of regular expressions. Do not spend much time on this slide, but encourage students to refer to the .NET Framework SDK, especially for details about using the regular expression classes.

Regular expressions provide a powerful, flexible, and efficient method to process text. The extensive pattern-matching notation of regular expressions allows you to quickly parse large amounts of text to find specific character patterns; to extract, edit, replace, or delete text substrings; and to add the extracted strings to a collection in order to generate a report.

For many applications that deal with strings, such as HTML processing, log file parsing, and HTTP header parsing, regular expressions are an essential tool.

The .NET Framework regular expressions incorporate the most popular features of other regular expression implementations, such as those used in Perl and awk. Designed to be compatible with Perl 5 regular expressions, .NET Framework regular expressions include features that are not yet available in other implementations, such as right-to-left matching and dynamic compilation.

The .NET Framework regular expression classes are part of the .NET Framework class library and can be used with any language or tool that targets the common language runtime, including ASP.NET and Microsoft

Visual Studio® .NET.

A detailed explanation of how to use the regular expression classes is beyond the scope of this course. For more information about using regular expression classes, see the .NET Framework SDK documentation.

20

Module 7: Strings, Arrays, and Collections

Terminology – Collections

Topic Objective

To define the term collection as it is used in this module and to identify where collections are found in the

.NET Framework.

Lead-in

In this module, the term collection is used in its broader sense: to describe a group of items.

!In This Module, the Term Collection Is Used in Its Broader Sense to Refer to a Group of Items

!In the .NET Framework, Collections Are Found in the Namespaces

#System.Array

#System.Collections

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Do not spend much time on this slide. The objective of this slide is to define the term collection clearly, before discussing the collections that are found in the .NET Framework.

In this module, the term collection is used in its broader sense to refer to a group of items. In the .NET Framework, examples of collections are found in the namespaces System.Array, and System.Collections.

Module 7: Strings, Arrays, and Collections

21

 

 

 

" .NET Framework Arrays

Topic Objective

To introduce the topics in the section.

Lead-in

The System.Array class is the base class of all array types and contains methods for creating, manipulating, searching, and sorting arrays.

!System.Array

!C# Specifics

!Iterating Over

!Comparing

!Sorting

*****************************ILLEGAL FOR NON-TRAINER USE******************************

The System.Array class is the base class of all array types and contains methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the Collections namespace. However, it is still a collection because it is based on the IList interface.

In an array style of collection, an item in the collection is referred to by the term element. Specific elements are identified by their array index. The low bound or lower bound of an Array is the index of its first element.

To understand the functionality of the various collection classes, you must understand their key interfaces. In this section, you will learn about the interfaces that are used by the methods of System.Array.

22

Module 7: Strings, Arrays, and Collections

System.Array

Topic Objective

To explain how array types are used and defined.

Lead-in

The System.Array class is the base class of all array types and contains methods for creating, manipulating, searching, and sorting arrays.

!System.Array Is the Base Class of All Array Types

!Arrays Implement the Following Interfaces

#ICloneable, IList, ICollection, and IEnumerable

!System.Array Has Methods For

#Creating, manipulating, searching, and sorting

!Null, Empty String, and Empty (0 item) Arrays Should Be Treated the Same

#Therefore, return an Empty array, instead of a null reference

*****************************ILLEGAL FOR NON-TRAINER USE******************************

The System.Array class is the base class of all array types and contains methods for creating, manipulating, searching, and sorting arrays. Arrays are always allocated on the garbage-collected heap. Arrays can be single dimensional or multidimensional. You can also create arrays of arrays, called jagged arrays.

For optimum performance, it is highly recommended that each rank of an array be zero-based. Additionally, each rank of an array must be zero-based when passing arrays between programming languages.

Defining an Array Type

You define an array type by specifying the element type of the array, the rank, or number of dimensions, of the array, and the upper and lower bounds of each dimension of the array. All of these details are included in any signature of an array type.

The runtime automatically creates exact array types as they are required. No separate definition of the array type is needed. Arrays of a particular type can only hold elements of that type. If you need to manipulate a set of unlike objects or value types, consider using one of the collection types that are defined in the System.Collections namespace.

Module 7: Strings, Arrays, and Collections

23

 

 

 

Methods and Properties of System.Array

Some of the methods and properties for the System.Array class are described in this topic. Many of these methods are used to implement the class’s interfaces.

System.Array implements the interfaces that are described in the following table.

Interface

Use

ICloneable

Supports cloning, which creates a new instance of a class with the

 

same value as an existing instance.

IList

Represents a collection of objects that can be individually

 

indexed.

ICollection

Defines size, enumerators, and synchronization methods for all

 

collections.

IEnumerable

Exposes the enumerator, which supports a simple iteration over a

 

collection.

The interfaces that are listed in the preceding table are supported not only by arrays but also by many of the System.Collections classes. Subsequent topics in this module discuss specific interfaces and the classes that implement them.

The following tables describe some of the public members that are available through the System.Array class.

Static Method

Use

BinarySearch Overloaded. Searches a one-dimensional sorted Array for a value, using a binary search algorithm.

CreateInstance Overloaded. Initializes a new instance of the Array class.

Sort Overloaded. Sorts the elements in one-dimensional Array objects.

Property

Use

IsFixedSize

Gets a value that indicates whether the Array has a fixed size.

IsReadOnly

Gets a value that indicates whether the Array is read-only.

Length

Gets the total number of elements in all of the dimensions of the

 

Array.

Rank

Gets the rank (number of dimensions) of the Array.

Note The IsFixedSize and IsReadOnly properties are always false unless they are overridden by a derived class.

24

Module 7: Strings, Arrays, and Collections

The following table describes some of the public instance methods that are available through the System.Array class.

Instance Method

Use

Clone

Creates a shallow copy of the Array.

GetEnumerator

Returns an IEnumerator for the Array.

GetLength

Gets the number of elements in the specified dimension of the

 

Array.

GetLowerBound

Gets the lower bound of the specified dimension in the Array.

GetUpperBound

Gets the upper bound of the specified dimension in the Array.

GetValue

Overloaded. Gets the values of the Array elements at the

 

specified indexes.

SetValue

Overloaded. Sets the specified Array elements to the specified

 

value.

For complete lists of public members of the System.Array class, see “Array Members” in the .NET Framework SDK documentation.

Empty Arrays

Nulls should only be returned by reference properties that refer to another object or component. String and Array properties should never return null, because a programmer typically does not expect null in this context. For example, a programmer typically would assume that the following code works:

public void DoSomething(…) { string[] sa = SomeOtherFunc();

// The following line assumes sa is never null if (sa.Length > 0) {

// do something else

}

}

Generally, null, empty string, and empty (0 item) arrays should be treated in the same way. Therefore, return an Empty array, instead of a null reference.

Module 7: Strings, Arrays, and Collections

25

 

 

 

C# Specifics

Topic Objective

To explain features that are unique to C# arrays.

Lead-in

C# arrays are similar to arrays in most other popular languages, but you should be aware of the differences that are presented in this topic.

!C# Array Indexes Start at Zero

!Declaring an Array – Size Is Not Part of Its Type

int[] numbers; // declare numbers as int[] numbers; // declare numbers as

// an int array of any size // an int array of any size

! Creating an Array

int[] numbers = new int[5]; // declare and create int[] numbers = new int[5]; // declare and create

! Initializing an Array

int[] numbers = new int[5] {1, 2, 3, 4, 5}; int[] numbers = new int[5] {1, 2, 3, 4, 5};

! Using System.Array Members

int[] numbers = {1, 2, 3, 4, 5}; int[] numbers = {1, 2, 3, 4, 5};

int LengthOfNumbers = numbers.Length; int LengthOfNumbers = numbers.Length;

*****************************ILLEGAL FOR NON-TRAINER USE******************************

C# arrays are zero-indexed. That means the array indexes start at zero. Arrays in C# and arrays in most other popular languages work similarly, but there are a few differences that you should be aware of.

When declaring an array, the brackets ([]) must come after the type, and not after the identifier. Placing the brackets after the identifier is not legal syntax in C#, as shown in the following example:

int[] table; // not int table[];

In addition, and unlike the C language, the size of the array is not part of its type. This allows you to declare and assign to an array any array of int objects, regardless of the array’s length, as in the following examples.

int[] numbers; // declare numbers as an int array of any size numbers = new int[10]; // numbers is a 10-element array numbers = new int[20]; // now it's a 20-element array

26

Module 7: Strings, Arrays, and Collections

Declaring an Array

C# supports single-dimensional arrays and multidimensional arrays, which are also know as rectangular arrays, and jagged arrays.

The following code examples show how to declare each of these arrays:

int[] numbers; // single-dimensional array

string[,] names; // multidimensional array

byte[][] scores; //Array-of-arrays

Instantiating an Array

Declaring arrays, as shown in the preceding examples, does not actually create the arrays. As discussed later in this topic, arrays in C# are objects and must be instantiated.

The following code examples show the syntax to create an array for each of the arrays already discussed:

int[] numbers = new int[5]; // Single-dimensional array

string[,] names = new string[5,4]; // Multi-dimensional array

byte[][] scores = new byte[5][]; // Array-of-arrays for (int x = 0; x < scores.Length; x++)

{

scores[x] = new byte[4];

}

Module 7: Strings, Arrays, and Collections

27

 

 

 

The following example shows a complete C# program that declares and instantiates arrays as discussed in this topic.

using System;

class DeclareArraysSample

{

public static void Main()

{

//Single-dimensional array int[] numbers = new int[5];

//Multidimensional array string[,] names = new string[5,4];

//Array-of-arrays (jagged array) byte[][] scores = new byte[5][];

//Create the jagged array

for (int i = 0; i < scores.Length; i++)

{

scores[i] = new byte[i+3];

}

// Print length of each row

for (int i = 0; i < scores.Length; i++)

{

Console.WriteLine("Length of row {0} is {1}", i, scores[i].Length);

}

}

}

The preceding program displays the following output:

Length of row 0 is 3

Length of row 1 is 4

Length of row 2 is 5

Length of row 3 is 6

Length of row 4 is 7

Initializing Arrays

C# provides simple and straightforward ways to initialize arrays when they are declared, by enclosing the initial values in curly braces ( {} ).

Important If an array is not initialized when it is declared, array members are automatically initialized to the default initial value for the array type.

28

Module 7: Strings, Arrays, and Collections

Single-Dimensional Array

The following examples show different ways to initialize single-dimensional arrays:

int[] numbers = new int[5] {1, 2, 3, 4, 5};

string[] names = new string[3] {"Matt", "Joanne", "Robert"};

You can omit the size of the array, as in the following examples:

int[] numbers = new int[] {1, 2, 3, 4, 5};

string[] names = new string[] {"Matt", "Joanne", "Robert"};

If an initializer is provided, you can also omit the new statement, as in the following examples:

int[] numbers = {1, 2, 3, 4, 5};

string[] names = {"Matt", "Joanne", "Robert"};

Multidimensional Array

The following examples show different ways to initialize multidimensional arrays:

int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };

string[,] siblings = new string[2, 2] { {"Mike","Amy"}, {"Mary","Albert"} };

You can omit the size of the array, as in the following examples:

int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} };

string[,] siblings = new string[,] { {"Mike","Amy"}, {"Mary","Ray"} };

If an initializer is provided, you can also omit the new statement, as in the following examples:

int[,] numbers = { {1, 2}, {3, 4}, {5, 6} };

string[,] siblings = { {"Mike", "Amy"}, {"Mary", "Albert"} };

Соседние файлы в папке c#