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 void PrintName(string FirstName, string LastName) {

Console.WriteLine("{0} {1}", FirstName, LastName);

}

}

Here, the PrintName()method is overloaded — once with no parameter and again with two input parameters. Notice that the second PrintName()method is prefixed with the Obsoleteattribute:

[Obsolete("This method is obsolete. Please use PrintName()")]

That basically marks the method as one that is not recommended for use. The class will still compile, but when you try to use this method, a warning will appear (see Figure 4-7).

Figure 47 The Obsoleteattribute is overloaded if you pass in truefor the - фото 109

Figure 4-7

The Obsoleteattribute is overloaded — if you pass in truefor the second parameter, the message set in the first parameter will be displayed as an error (by default the message is displayed as a warning):

[Obsolete("This method is obsolete. Please use PrintName()", true)]

Figure 4-8 shows the error message displayed when you use the PrintName()method marked with the Obsoleteattribute with the second parameter set to true.

Figure 48 Attributes can also be applied to a class In the following example - фото 110

Figure 4-8

Attributes can also be applied to a class. In the following example, the Obsoleteattribute is applied to the Contactclass:

[Obsolete("This class is obsolete. Please use NewContact")]

class Contact {

//...

}

Custom Attributes

You can also define your own custom attributes. To do so, you just need to define a class that inherits directly from System.Attribute. The following Programmerclass is one example of a custom attribute:

public class Programmer : System.Attribute {

private string _Name;

public double Version;

public string Dept { get; set; }

public Programmer(string Name) {

this._Name = Name;

}

}

In this attribute, there are:

□ One private member ( _Name)

□ One public member ( Version)

□ One constructor, which takes in one string argument

Here's how to apply the Programmerattribute to a class:

[Programmer("Wei-Meng Lee", Dept="IT", Version=1.5)]

class Contact {

//...

}

You can also apply the Programmerattribute to methods (as the following code shows), properties, structure, and so on:

[Programmer("Wei-Meng Lee", Dept="IT", Version=1.5)]

class Contact {

[Programmer("Jason", Dept = "CS", Version = 1.6)]

public void PrintName() {

Console.WriteLine("{0} {1}", this.FirstName, this.LastName);

}

//...

}

Use the AttributeUsageattribute to restrict the use of any attribute to certain types:

[System.AttributeUsage(System.AttributeTargets.Class |

System.AttributeTargets.Method |

System.AttributeTargets.Property)]

public class Programmer : System.Attribute {

private string _Name;

public double Version;

public string Dept { get; set; }

public Programmer(string Name) {

this._Name = Name;

}

}

In this example, the Programmerattribute can only be used on class definitions, methods, and properties.

Structures

An alternative to using classes is to use a struct (for structure). A struct is a lightweight user-defined type that is very similar to a class, but with some exceptions:

□ Structs do not support inheritance or destructors.

□ A struct is a value type (class is a reference type).

□ A struct cannot declare a default constructor.

Structs implicitly derive from objectand unlike classes, a struct is a value type. This means that when an object is created from a struct and assigned to another variable, the variable will contain a copy of the struct object.

Like classes, structs support constructor, properties, and methods. The following code shows the definition for the Coordinatestruct:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace WindowsFormsApplication1 {

public partial class Form1 : Form {

public Form1() {

InitializeComponent();

}

}

}

public struct Coordinate {

public double latitude { get; set; }

public double longitude { get; set; }

}

The Coordinatestruct contains two properties (defined using the automatic properties feature). You can add a constructor to the struct if you want:

public struct Coordinate {

public double latitude { get; set; }

public double longitude { get; set; }

public Coordinate(double lat, double lng) {

latitude = lat;

longitude = lng;

}

}

Remember, a struct cannot have a default constructor.

Note that the compiler will complain with the message "Backing field for automatically implemented property 'Coordinate.latitude' must be fully assigned before control is returned to the caller" when you try to compile this application. This restriction applies only to structs (classes won't have this problem). To resolve this, you need to call the default constructor of the struct, like this:

public struct Coordinate {

public double latitude { get; set; }

public double longitude { get; set; }

public Coordinate(double lat, double lng) :

this() {

latitude = lat;

longitude = lng;

}

}

You can also add methods to a struct. The following shows the ToString()method defined in the Coordinatestruct:

public struct Coordinate {

public double latitude { get; set; }

public double longitude { get; set; }

public Coordinate(double lat, double lng) :

this() {

latitude = lat;

longitude = lng;

}

public override string ToString() {

return latitude + "," + longitude;

}

}

To use the Coordinatestruct, create a new instance using the newkeyword and then initialize its individual properties:

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

Интервал:

Закладка:

Сделать

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

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


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

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

x