public T Pop() {
_pointer--;
if (_pointer < 0) {
return default(T);
}
return _elements[_pointer];
}
For instance, if the stack deals with int
values, calling the Pop()
method on an empty stack will return 0:
MyStack stack = new MyStack(3);
stack.Push(1);
stack.Push(2);
stack.Push(3);
Console.WriteLine(stack.Pop()); //---3---
Console.WriteLine(stack.Pop()); //---2---
Console.WriteLine(stack.Pop()); //---1---
Console.WriteLine(stack.Pop()); //---0---
Likewise, if the stack deals with the string type, calling Pop()
on an empty stack will return an empty string:
MyStack stack = new MyStack(3);
stack.Push("A");
stack.Push("B");
stack.Push("C");
Console.WriteLine(stack.Pop()); //---"C"---
Console.WriteLine(stack.Pop()); //---"B"---
Console.WriteLine(stack.Pop()); //---"A"---
Console.WriteLine(stack.Pop()); //---""---
The default
keyword returns null
for reference types (that is, if T
is a reference type) and 0 for numeric types. If the type is a struct
, it will return each member of the struct initialized to 0 (for numeric types) or null
(for reference types).
It's not difficult to see the advantages of using generics:
□ Type safety— Generic types enforce type compliance at compile time, not at runtime (as in the case of using Object
). This reduces the chances of data-type conflict during runtime.
□ Performance— The data types to be used in a generic class are determined at compile time, so there's no need to perform type casting during runtime, which is a computationally costly process.
□ Code reuse— Because you need to write the class only once and then customize it for use with the various data types, there is a substantial amount of code reuse.
Using Constraints in a Generic Type
Using the MyStack
class, suppose that you want to add a method called Find()
that allows users to check if the stack contains a specific item. You implement the Find()
method like this:
public class MyStack {
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);
//throw new Exception("Stack is empty.");
}
return _elements[_pointer];
}
public bool Find(T keyword) {
bool found = false;
for (int i=0; i<_pointer; i++) {
if (_elements[i] == keyword) {
found = true;
break;
}
}
return found;
}
}
But the code will not compile. This is because of the statement:
if (_elements[i] == keyword)
That's because the compiler has no way of knowing if the actual type of item
and keyword
(type T
) support this operator (see Figure 9-3). For example, you cannot by default compare
two struct objects.
Figure 9-3
A better way to resolve this problem is to apply constraint to the generic class so that only certain data types can be used. In this case, because you want to perform comparison in the Find()
method, the data type used by the generic class must implement the IComparable
interface. This is enforced by using the where
keyword:
public class MyStack where T : IComparable {
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;
}
}
For the comparison, you use the CompareTo()
method to compare two items of type T
(which must implement the IComparable
interface). The CompareTo()
method returns 0 if the two objects are equal. You can now search for an item by using the Find()
method:
MyStack stack = new MyStack(3);
stack.Push("A");
stack.Push("B");
stack.Push("C");
if (stack.Find("B")) Console.WriteLine("Contains B");
In this case, the code works because the string
type implements the IComparable
interface. Suppose that you have the following Employee
class definition:
public class Employee {
public string ID { get; set; }
public string Name { get; set; }
}
When you try to use the MyStack
class with the Employee
class, you get an error:
MyStack stack = new MyStack(3); //---Error---
That's because the Employee
class does not implement the IComparable
interface. To resolve this, simply implement the IComparable
interface in the Employee
class and implement the CompareTo()
method:
public class Employee : IComparable {
public string ID { get; set; }
public string Name { get; set; }
public int CompareTo(Employee obj) {
return this.ID.CompareTo(obj.ID);
}
}
You can now use the Employee
class with the generic MyStack
class:
MyStack stack = new MyStack(2);
stack.Push(new Employee() { ID = "123", Name = "John" });
Читать дальше