logo search
CSharp_Prog_Guide

Создание класса Writer

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

using System;

using System.IO;

public class MyWriter

{

private Stream s;

public MyWriter(Stream stream)

{

s = stream;

}

public void WriteDouble(double myData)

{

byte[] b = BitConverter.GetBytes(myData);

// GetBytes is a binary representation of a double data type.

s.Write(b, 0, b.Length);

}

public void Close()

{

s.Close();

}

}

В этом примере создается класс с конструктором, аргументом которого является поток. Поэтому есть возможность в дальнейшем обращаться к любым необходимым методам Write. Необходимо преобразовать данные, предназначенные для записи, в массив byte[]. После получения массива byte[] метод Write записывает его в поток s.

Collections and Data Structures

Closely related data can be handled more efficiently when grouped together into a collection. Instead of writing separate code to handle each individual object, you can use the same code to process all the elements of a collection.

To manage a collection, use the Array class and the System.Collections classes to add, remove, and modify either individual elements of the collection or a range of elements. An entire collection can even be copied to another collection.

Some Collections classes have sorting capabilities, and most are indexed. Memory management is handled automatically, and the capacity of a collection is expanded as required. Synchronization provides thread safety when accessing members of the collection. Some Collections classes can generate wrappers that make the collection read-only or fixed-size. Any Collections class can generate its own enumerator that makes it easy to iterate through the elements.

In the .NET Framework version 2.0, generic collection classes provide new functionality and make it easy to create strongly typed collections. See the System.Collections.Generic and System.Collections.ObjectModel namespaces.

The LINQ to Objects feature allows you to use LINQ queries to access in-memory objects as long as the object type implements IEnumerable or IEnumerable<(Of <(T>)>). LINQ queries provide a common pattern for accessing data; are typically more concise and readable than standard foreach loops; and provide filtering, ordering and grouping capabilities. LINQ queries can also improve performance.