Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

public T Pop() {

_pointer--;

if (_pointer < 0) {

return default(T);

}

return _elements[_pointer];

}

For instance, if the stack deals with intvalues, 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 defaultkeyword returns nullfor reference types (that is, if Tis 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).

Advantages of Generics

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 MyStackclass, 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 itemand keyword(type T) support this operator (see Figure 9-3). For example, you cannot by default comparetwo struct objects.

Figure 93 A better way to resolve this problem is to apply constraint to the - фото 140

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 IComparableinterface. This is enforced by using the wherekeyword:

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 IComparableinterface). 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 stringtype implements the IComparableinterface. Suppose that you have the following Employeeclass definition:

public class Employee {

public string ID { get; set; }

public string Name { get; set; }

}

When you try to use the MyStackclass with the Employeeclass, you get an error:

MyStack stack = new MyStack(3); //---Error---

That's because the Employeeclass does not implement the IComparableinterface. To resolve this, simply implement the IComparableinterface in the Employeeclass 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 Employeeclass with the generic MyStackclass:

MyStack stack = new MyStack(2);

stack.Push(new Employee() { ID = "123", Name = "John" });

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x