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

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

Интервал:

Закладка:

Сделать

d.Method('C');

If hiding Method(int num)in BaseClassis your true intention, use the newkeyword to denote that as follows (or else the compiler will issue a warning):

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

public new void Method(int num) {

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

}

In C#, you use the newkeyword to hide methods in the base class by signature. C# does not support hiding methods by name as is possible in VB.NET by using the Shadowskeyword.

The following table summarizes the different keywords used for inheritance.

Modifier Description
new Hides an inherited method with the same signature.
static A member that belongs to the type itself and not to a specific object.
virtual A method that can be overridden by a derived class.
abstract Provides the signature of a method/class but does not contain any implementation.
override Overrides an inherited virtual or abstract method.
sealed A method that cannot be overridden by derived classes; a class that cannot be inherited by other classes.
extern An "extern" method is one in which the implementation is provided elsewhere and is most commonly used to provide definitions for methods invoked using .NET interop.

Overloading Operators

Besides overloading methods, C# also supports the overloading of operators (such as +, -, /, and *). Operator overloading allows you to provide your own operator implementation for your specific type. To see how operator overloading works, consider the following program containing the Point class representing a point in a coordinate system:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace OperatorOverloading {

class Program {

static void Main(string[] args) {}

}

class Point {

public Single X { get; set; }

public Single Y { get; set; }

public Point(Single X, Single Y) {

this.X = X;

this.Y = Y;

}

public double DistanceFromOrigin() {

return (Math.Sqrt(Math.Pow(this.X, 2) + Math.Pow(this.Y, 2)));

}

}

}

The Pointclass contains two public properties ( Xand Y), a constructor, and a method — DistanceFromOrigin().

If you constantly perform calculations where you need to add the distances of two points (from the origin), your code may look like this:

static void Main(string[] args) {

Point ptA = new Point(4, 5);

Point ptB = new Point(2, 7);

double distanceA, distanceB;

distanceA = ptA.DistanceFromOrigin(); //---6.40312423743285---

distanceB = ptB.DistanceFromOrigin(); //---7.28010988928052---

Console.WriteLine(distanceA + distanceB); //---13.6832341267134---

Console.ReadLine();

}

A much better implementation is to overload the +operator for use with the Pointclass. To overload the +operator, define a public static operator within the Pointclass as follows:

class Point {

public Single X { get; set; }

public Single Y { get; set; }

public Point(Single X, Single Y) {

this.X = X;

this.Y = Y;

}

public double DistanceFromOrigin() {

return (Math.Sqrt(Math.Pow(this.X, 2) + Math.Pow(this.Y, 2)));

}

public static double operator +(Point A, Point B) {

return (A.DistanceFromOrigin() + B.DistanceFromOrigin());

}

}

The operatorkeyword overloads a built-in operator. In this example, the overloaded +operator allows it to "add" two Pointobjects by adding the result of their DistanceFromOrigin()methods:

static void Main(string[] args) {

Point ptA = new Point(4, 5);

Point ptB = new Point(2, 7);

Console.WriteLine(ptA + ptB); //---13.6832341267134---

Console.ReadLine();

}

You can also use the operatorkeyword to define a conversion operator, as the following example shows:

class Point {

public Single X { get; set; }

public Single Y { get; set; }

public Point(Single X, Single Y) {

this.X = X;

this.Y = Y;

}

public double DistanceFromOrigin() {

return (Math.Sqrt(Math.Pow(this.X, 2) + Math.Pow(this.Y, 2)));

}

public static double operator +(Point A, Point B) {

return (A.DistanceFromOrigin() + B.DistanceFromOrigin());

}

public static implicit operator double(Point pt) {

return (pt.X / pt.Y);

}

}

Here, the implicitkeyword indicates that you want to implicitly perform a conversion of the Pointclass to a doublevalue (this value is defined to be the ratio of the X and Y coordinates).

Now when you assign a Pointobject to a double variable, the ratio of the Xand Ycoordinates is assigned automatically, as the following statements prove:

static void Main(string[] args) {

Point ptA = new Point(4, 5);

Point ptB = new Point(2, 7);

double ratio = ptA; //---implicitly convert to a double type---

ptB = ptA; //---assign to another Point object---

Console.WriteLine(ratio); //---0.8---

Console.WriteLine((double)ptB); //---0.8---

Console.ReadLine();

}

Extension Methods (C# 3.0)

Whenever you add additional methods to a class in previous versions of C#, you need to subclass it and then add the required method. For example, consider the following predefined (meaning you cannot modify it) classes:

public abstract class Shape {

//---properties---

public double length { get; set; }

public double width { get; set; }

//---make this method as virtual---

public virtual double Perimeter() {

return 2 * (this.length + this.width);

}

//---abstract method---

public abstract double Area();

}

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

Интервал:

Закладка:

Сделать

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

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


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

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

x