Книга: C# 2008 Programmer

Generic Operators

Generic Operators

Generics can also be applied to operators. Consider the generic MyStack class discussed earlier in this chapter. Suppose that you want to be able to join two MyStack objects together, like this:

MyStack<string> stack1 = new MyStack<string>(4);
stack1.Push("A");
stack1.Push("B");
MyStack<string> stack2 = new MyStack<string>(2);
stack2.Push("C");
stack2.Push("D");
stack1 += stack2;

In this case, you can overload the + operator, as highlighted in the following code:

public class MyStack<T> where T : IComparable<T> {
 private T[] _elements;
 private int _pointer;
 public MyStack(int size) {
  _elements = new T[size];
  _pointer = 0;
 }
 public void Push(T item) {
  if (_pointer < _elements.Length - 1) {
   throw new Exception("Stack is full.");
  }
  _elements[_pointer] = item;
  _pointer++;
 }
 public T Pop() {
  _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
A

Оглавление книги


Генерация: 0.030. Запросов К БД/Cache: 0 / 0
поделиться
Вверх Вниз