_pointer--;

  if (_pointer < 0) {

   return default(T);

  }

  return _elements[_pointer];

 }

 public bool Find(T keyword) {

  bool found = false;

  for (int i = 0; i < _pointer; i++) {

   if (_elements[i].CompareTo(keyword) == 0) {

    found = true;

    break;

   }

  }

  return found;

 }

 public bool Empty {

  get {

   return (_pointer <= 0);

  }

 }

 public static MyStack<T> operator +

  (MyStack<T> stackA, MyStack<T> stackB) {

  while (IstackB.Empty) {

   T item = stackB.Pop();

   stackA.Push(item);

  }

  return stackA;

 }

}

The + operator takes in two operands — the generic MyStack objects. Internally, you pop out each element from the second stack and push it into the first stack. The Empty property allows you to know if a stack is empty.

To print out the elements of stack1 after the joining, use the following statements:

stack1 += stack2;

while (!stack1.Empty)

Console.WriteLine(stack1.Pop());

Here's the output:

C

D

B

A

Generic Delegates

You can also use generics on delegates. The following class definition contains a generic delegate, MethodDelegate:

public class SomeClass<T> {

 public delegate void MethodDelegate(T t);

  public void DoSomething(T t) {

 }

}

When you specify the type for the class, you also need to specify it for the delegate:

SomeClass<int> sc = new SomeClass<int>();

SomeClass<int>.MethodDelegate del;

del = new SomeClass<int>.MethodDelegate(sc.DoSomething);

You can make direct assignment to the delegate using a feature known as delegate inferencing, as the following code shows:

del = sc.DoSomething;

Generics and the .NET Framework Class Library

The .NET Framework class library contains a number of generic classes that enable users to create strongly typed collections. These classes are grouped under the System.Collections.Generic namespace (the nongeneric versions of the classes are contained within the System.Collections namespace). The following tables show the various classes, structures, and interfaces contained within this namespace.

The following table provides a look at the classes contained within the System.Collections.Generic namespace.

Class Description
Comparer<(Of <(T>)>) Provides a base class for implementations of the IComparer<(Of <(T>)>) generic interface.
Dictionary<(Of <(TKey, TValue>)>) Represents a collection of keys and values.
Dictionary<(Of <(TKey, TValue>)<)..::.KeyCollection Represents the collection of keys in a Dictionary<(Of <(TKey, TValue>)>) . This class cannot be inherited.
Dictionary<(Of <(TKey, TValue>)>)..::.ValueCollection Represents the collection of values in a Dictionary<(Of <(TKey, TValue>) >). This class cannot be inherited.
EqualityComparer<(Of <(T>)>)
Вы читаете C# 2008 Programmer's Reference
Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

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

Отметить Добавить цитату