Tải bản đầy đủ - 0 (trang)
2-12. Create a Generic Type

2-12. Create a Generic Type

Tải bản đầy đủ - 0trang

CHAPTER 2 ■ DATA MANIPULATION



This declaration specifies a new class named MyGenericType, which uses three generic types in its

implementation (T1, T2, and T3). When implementing the type, you substitute the generic type names

into the code instead of using specific type names. For example, one method might take an argument of

type T1 and return a result of type T2, as shown here:

public T2 MyGenericMethod(T1 arg)

When other people use your class and create an instance of it, they specify the actual types to use as

part of the instantiation. Here is an example:

MyGenericType obj = new MyGenericType();

The types specified replace T1, T2, and T3 throughout the implementation, so with this instance,

MyGenericMethod would actually be interpreted as follows:

public Stream MyGenericMethod(string arg)

You can also include constraints as part of your generic type definition. This allows you to make

specifications such as the following:





Only value types or only reference types can be used with the generic type.







Only types that implement a default (empty) constructor can be used with the

generic type.







Only types that implement a specific interface can be used with the generic type.







Only types that inherit from a specific base class can be used with the

generic type.







One generic type must be the same as another generic type (for example, T1 must

be the same as T3).



For example, to specify that T1 must implement the System.IDisposable interface and provide a

default constructor, that T2 must be or derive from the System.IO.Stream class, and that T3 must be the

same type as T1, change the definition of MyGenericType as follows:

public class MyGenericType

where T1 : System.IDisposable, new()

where T2 : System.IO.Stream

where T3 : T1

{ \* ...Implementation... *\ }



The Code

The following example demonstrates a simplified bag implementation that returns those objects put

into it at random. A bag is a data structure that can contain zero or more items, including duplicates of

items, but does not guarantee any ordering of the items it contains.

using System;

using System.Collections.Generic;



84



www.it-ebooks.info



CHAPTER 2 ■ DATA MANIPULATION



namespace Apress.VisualCSharpRecipes.Chapter02

{

public class Bag

{

// A List to hold the bags's contents. The list must be

// of the same type as the bag.

private List items = new List();

// A method to add an item to the bag.

public void Add(T item)

{

items.Add(item);

}

// A method to get a random item from the bag.

public T Remove()

{

T item = default(T);

if (items.Count != 0)

{

// Determine which item to remove from the bag.

Random r = new Random();

int num = r.Next(0, items.Count);

// Remove the item.

item = items[num];

items.RemoveAt(num);

}

return item;

}

// A method to provide an enumerator from the underlying list

public IEnumerator GetEnumerator()

{

return items.GetEnumerator();

}

// A method to remove all items from the bag and return them

// as an array

public T[] RemoveAll()

{

T[] i = items.ToArray();

items.Clear();

return i;

}

}



85



www.it-ebooks.info



CHAPTER 2 ■ DATA MANIPULATION



public class Recipe02_12

{

public static void Main(string[] args)

{

// Create a new bag of strings.

Bag bag = new Bag();

// Add strings to the bag.

bag.Add("Darryl");

bag.Add("Bodders");

bag.Add("Gary");

bag.Add("Mike");

bag.Add("Nigel");

bag.Add("Ian");

Console.WriteLine("Bag contents are:");

foreach (string elem in bag)

{

Console.WriteLine("Element: {0}", elem);

}

// Take four strings from the

Console.WriteLine("\nRemoving

Console.WriteLine("Removing =

Console.WriteLine("Removing =

Console.WriteLine("Removing =

Console.WriteLine("Removing =



bag and display.

individual elements");

{0}", bag.Remove());

{0}", bag.Remove());

{0}", bag.Remove());

{0}", bag.Remove());



Console.WriteLine("\nBag contents are:");

foreach (string elem in bag)

{

Console.WriteLine("Element: {0}", elem);

}

// Remove the remaining items from the bag.

Console.WriteLine("\nRemoving all elements");

string[] s = bag.RemoveAll();

Console.WriteLine("\nBag contents are:");

foreach (string elem in bag)

{

Console.WriteLine("Element: {0}", elem);

}

// Wait to continue.

Console.WriteLine("\nMain method complete. Press Enter");

Console.ReadLine();

}

}

}



86



www.it-ebooks.info



CHAPTER 2 ■ DATA MANIPULATION



2-13. Store a Serializable Object to a File

Problem

You need to store a serializable object and its state to a file, and then deserialize it later.



Solution

Use a formatter to serialize the object and write it to a System.IO.FileStream object. When you need to

retrieve the object, use the same type of formatter to read the serialized data from the file and deserialize

the object. The .NET Framework class library includes the following formatter implementations for

serializing objects to binary or SOAP format:





System.Runtime.Serialization.Formatters.Binary.BinaryFormatter







System.Runtime.Serialization.Formatters.Soap.SoapFormatter



How It Works

Using the BinaryFormatter and SoapFormatter classes, you can serialize an instance of any serializable

type. (See recipe 13-1 for details on how to make a type serializable.) The BinaryFormatter class

produces a binary data stream representing the object and its state. The SoapFormatter class produces a

SOAP document.

Both the BinaryFormatter and SoapFormatter classes implement the interface

System.Runtime.Serialization.IFormatter, which defines two methods: Serialize and Deserialize.

The Serialize method takes a System.IO.Stream reference and a System.Object reference as arguments,

serializes the Object, and writes it to the Stream. The Deserialize method takes a Stream reference as an

argument, reads the serialized object data from the Stream, and returns an Object reference to a

deserialized object. You must cast the returned Object reference to the correct type.



■ Note You will need to reference the System.Runtime.Serialization.Formatters.Soap assembly in order to

use SoapFormatter. The BinaryFormatter class is contained in the core assembly and requires no additional

project references



The Code

The example shown here demonstrates the use of both BinaryFormatter and SoapFormatter to serialize a

System.Collections.ArrayList object containing a list of people to a file. The ArrayList object is then

deserialized from the files and the contents displayed to the console.



87



www.it-ebooks.info



CHAPTER 2 ■ DATA MANIPULATION



using

using

using

using

using



System;

System.IO;

System.Collections;

System.Runtime.Serialization.Formatters.Soap;

System.Runtime.Serialization.Formatters.Binary;



namespace Apress.VisualCSharpRecipes.Chapter02

{

class Recipe02_13

{

// Serialize an ArrayList object to a binary file.

private static void BinarySerialize(ArrayList list)

{

using (FileStream str = File.Create("people.bin"))

{

BinaryFormatter bf = new BinaryFormatter();

bf.Serialize(str, list);

}

}

// Deserialize an ArrayList object from a binary file.

private static ArrayList BinaryDeserialize()

{

ArrayList people = null;

using (FileStream str = File.OpenRead("people.bin"))

{

BinaryFormatter bf = new BinaryFormatter();

people = (ArrayList)bf.Deserialize(str);

}

return people;

}

// Serialize an ArrayList object to a SOAP file.

private static void SoapSerialize(ArrayList list)

{

using (FileStream str = File.Create("people.soap"))

{

SoapFormatter sf = new SoapFormatter();

sf.Serialize(str, list);

}

}

// Deserialize an ArrayList object from a SOAP file.

private static ArrayList SoapDeserialize()

{

ArrayList people = null;



88



www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

2-12. Create a Generic Type

Tải bản đầy đủ ngay(0 tr)

×