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

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

Интервал:

Закладка:

Сделать

The outputs are:

Constructor in BaseClass

Constructor in DerivedClass

What happens if there is no default constructor in the base class, but perhaps a parameterized constructor like the following?

public class BaseClass {

//---constructor---

public BaseClass(int x) {

Console.WriteLine("Constructor in BaseClass");

}

}

In that case, the compiler will complain that BaseClassdoes not contain a default constructor.

Remember that if a base class contains constructors, one of them must be a default constructor.

Calling Base Class Constructors

Suppose BaseClasscontains two constructors — one default and one parameterized:

public class BaseClass {

//---default constructor---

public BaseClass() {

Console.WriteLine("Default constructor in BaseClass");

}

//---parameterized constructor---

public BaseClass(int x) {

Console.WriteLine("Parameterized Constructor in BaseClass");

}

}

And DerivedClasscontains one default constructor:

public class DerivedClass : BaseClass {

//---default constructor---

public DerivedClass() {

Console.WriteLine("Constructor in DerivedClass");

}

}

When an instance of the DerivedClassis created like this:

DerivedClass dc = new DerivedClass();

The default constructor in BaseClassis first invoked followed by the DerivedClass. However, you can choose which constructor you want to invoke in BaseClassby using the base keyword in the default constructor in DerivedClass, like this:

public class DerivedClass : BaseClass {

//---default constructor---

public DerivedClass(): base(4) {

Console.WriteLine("Constructor in DerivedClass");

}

}

In this example, when an instance of the DerivedClassis created, the parameterized constructor in BaseClassis invoked first (with the argument 4 passed in), followed by the default constructor in DerivedClass. This is shown in the output:

DerivedClass dc = new DerivedClass();

//---prints out:---

//Parameterized Constructor in BaseClass

//Constructor in DerivedClass

Figure 6-7 shows that IntelliSense lists the overloaded constructors in BaseClass.

Figure 67 Interface Inheritance When an interface inherits from a base - фото 117

Figure 6-7

Interface Inheritance

When an interface inherits from a base interface, it inherits all the base interface's functions signatures (but no implementation).

Let's explore the concept of interface inheritance by using the hierarchy of various classes defined earlier in the chapter, starting from the root class Shape, with the Circleand Rectangleclasses inheriting from it (the Square class in turn inherits from the Rectangleclass), as Figure 6-8 shows.

Figure 68 One problem with this class hierarchy is that for the Circleclass - фото 118

Figure 6-8

One problem with this class hierarchy is that for the Circleclass, using the inherited lengthproperty to represent the diameter is a bit awkward. Likewise, for the Squareclass the widthproperty should not be visible because the length and width of a square are the same. Hence, these classes could be better rearranged.

As you recall from Chapter 5, you can use an interface to define the signature of a class's members. Likewise, you can use interfaces to define the hierarchy of a set of classes. If you do so, developers who implement this set of classes will have to follow the rules as defined in the interfaces.

You can use interfaces to redefine the existing classes, as shown in Figure 6-9.

Figure 69 Here the IShapeinterface contains two methods Areaand - фото 119

Figure 6-9

Here, the IShapeinterface contains two methods — Area()and Perimeter():

public interface IShape {

//---methods---

double Perimeter();

double Area();

}

Remember, an interface simply defines the members in a class; it does not contain any implementation. Also, there is no modifier (like virtualor abstract) prefixing the function members here, so you need not worry about the implementation of the Perimeter()and Area()methods — they could be implemented by other derived classes.

The ICircleinterface inherits from the IShapeinterface and defines an additional radiusproperty:

public interface ICircle : IShape {

//---property---

double radius { get; set; }

}

The ISquareinterface inherits from the IShapeinterface and defines an additional lengthproperty:

public interface ISquare : IShape {

//---property---

double length { get; set; }

}

The IRectangleinterface inherits from both the IShapeand ISquareinterfaces. In addition, it also defines a widthproperty:

public interface IRectangle : IShape, ISquare {

//---property---

double width { get; set; }

}

So what does the implementation of these interfaces look like? First, implement the ISquareinterface, like this:

public class Square : ISquare {

//---property---

public double length { get; set; }

//---methods---

public double Perimeter() {

return 4 * (this.length);

}

public double Area() {

return (Math.Pow(this.length, 2));

}

}

Here, you provide the implementation for the length property as well as the two methods — Perimeter()and Area().

You not need to implement the IShapeclass because you can't provide any meaningful implementation of the Area()and Perimeter()methods here.

Because the IRectangleinterface inherits from both the ISquareand IShapeinterfaces and the ISquareinterface has already been implemented (by the Squareclass), you can simply inherit from the Squareclass and implement the IRectangleinterface, like this:

public class Rectangle : Square, IRectangle {

//---property---

public double width { get; set; }

}

If you implement the IRectangleinterface directly (without inheriting from the Squareclass, you need to provide the implementation of the length property as well as the methods Perimeter()and Area().

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

Интервал:

Закладка:

Сделать

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

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


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

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

x