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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

//...

}

}

When a class has multiple methods each with the same name but a different signature (parameter), the methods are known as overloaded. The Perimeter()method of the Circleclass is now overloaded (see Figure 6-2). Note that IntelliSense shows that the first method is from the Shapebase class, while the second one is from the Circleclass.

Figure 62 See the Overloading Methods section later in this chapter Sealed - фото 112

Figure 6-2

See the "Overloading Methods" section later in this chapter.

Sealed Classes and Methods

So far you've seen the class definition for Shape, Rectangle, and Circle. Now let's define a class for the shape Square. As you know, a square is just a special version of rectangle; it just happens to have the same length and width. In this case, the Squareclass can simply inherit from the Rectangleclass:

public class Square : Rectangle {}

You can instantiate the Squareclass as per normal and all the members available in the Rectanglewould then be available to it:

Square s = new Square();

s.length = 5;

s.width = 5;

Console.WriteLine(s.Perimeter()); //---20---

Console.WriteLine(s.Area()); //---25---

To ensure that no other classes can derive from the Square class, you can seal it using the sealedkeyword. A class prefixed with the sealedkeyword prevents other classes inheriting from it. For example, if you seal the Squareclass, like this:

public sealed class Square : Rectangle {}

The following will result in an error:

//---Error: Square is sealed---

public class Rhombus : Square {}

A sealed class cannot contain virtual methods. In the following example, the Squareclass is sealed, so it cannot contain the virtual method called Diagonal():

public sealed class Square : Rectangle {

//---Error: sealed class cannot contain virtual methods---

public virtual Single Diagonal() {

//---implementation here---

}

}

This is logical because a sealed class does not provide an opportunity for a derived class to implement its virtual method. By the same argument, a sealed class also cannot contain abstract methods:

public sealed class Square : Rectangle {

//---Error: sealed class cannot contain abstract method---

public abstract Single Diagonal();

}

You can also seal methods so that other derived classes cannot override the implementation that you have provided in the current class. For example, recall that the Rectangleclass provides the implementation for the abstract Area()method defined in the Shapeclass:

public class Rectangle : Shape {

public override double Area() {

return this.length * this.width;

}

}

To prevent the derived classes of Rectangle(such as Square) from modifying the Area()implementation, prefix the method with the sealedkeyword:

public class Rectangle : Shape {

public override sealed double Area() {

return this.length * this.width;

}

}

Now if you try to override the Area()method in the Squareclass, you get an error:

public sealed class Square : Rectangle {

//---Error: Area() is sealed in Rectangle class---

public override double Area() {

//---implementation here---

}

}

Overloading Methods

When you have multiple methods in a class having the same name but different signatures (parameters), they are known as overloaded methods. Consider the following class definition:

public class BaseClass {

public void Method(int num) {

Console.WriteLine("Number in BaseClass is " + num);

}

public void Method(string st) {

Console.WriteLine("String in BaseClass is " + st);

}

}

Here, BaseClasshas two methods called Method()with two different signatures — one integer and another one string.

When you create an instance of BaseClass, you can call Method()with either an integer or string argument and the compiler will automatically invoke the appropriate method:

BaseClass b = new BaseClass();

//---prints out: Number in BaseClass is 5---

b.Method(5);

//---prints out: String in BaseClass is This is a string---

b.Method("This is a string");

Suppose that you have another class inheriting from BaseClasswith a Method()method that has a different signature, like this:

public class DerivedClass : BaseClass {

//---overloads the method---

public void Method(char ch) {

Console.WriteLine("Character in DerivedClass is " + ch);

}

}

Then, DerivedClassnow has three overloaded Method()methods, as illustrated in Figure 6-3.

Figure 63 You can now pass three different types of arguments into Method - фото 113

Figure 6-3

You can now pass three different types of arguments into Method()— character, integer, and string:

DerivedClass d = new DerivedClass();

//---prints out: Character in DerivedClass is C---

d.Method('C');

//---prints out: Number in BaseClass is 5---

d.Method(5);

//---prints out: String in BaseClass is This is a string---

d.Method("This is a string");

What happens if you have a Method()having the same signature as another one in the base class, such as the following?

public class DerivedClass : BaseClass {

//---overloads the method with the same parameter list---

public void Method(int num) {

Console.WriteLine("Number in DerivedClass is " + num);

}

//---overloads the method

public void Method(char ch) {

Console.WriteLine("Character in DerivedClass is " + ch);

}

}

In this case, Method(int num)in DerivedClasswill hide the same method in BaseClass, as the following printout proves:

DerivedClass d = new DerivedClass();

//---prints out: Number in DerivedClass is 5---

d.Method(5);

//---prints out: String in BaseClass is This is a string---

d.Method("This is a string");

//---prints out: Character in DerivedClass is C---

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

Интервал:

Закладка:

Сделать

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

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


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

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

x