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

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

Интервал:

Закладка:

Сделать
Figure 313 To undefine a symbol you can use the undefpreprocessor directive - фото 94

Figure 3-13

To undefine a symbol, you can use the #undefpreprocessor directive, like this:

#undef DEBUG

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

...

If you recompile the program now, the debugging statement will be omitted.

Another popular way of using the #definepreprocessor directive is to omit the definition of the symbol and inject it during compilation time. For example, if you remove the #definepreprocessor directive from the program, you can define it using the /definecompiler option:

1. In Visual Studio 2008 command prompt, compile the program using:

csc Program.cs /define:DEBUG

2. Run the program by issuing the command:

Program.exe

The output is identical to what you saw in Figure 3-13 — the debugging statement prints out the intermediate results.

If you now recompile the program by defining another symbol (other than DEBUG), you will realize that the debugging output does not appear (see Figure 3-14).

Figure 314 if else elif and endif As you saw in the preceding - фото 95

Figure 3-14

#if, #else, #elif, and #endif

As you saw in the preceding section, the #ifand #endifpreprocessor directives defines a block of code to include for compilation if a specified symbol is defined. You can also use the #else and #elif preprocessor directives to create compound conditional directives.

Using the previous example, you can add the #elseand #elifpreprocessor directives as follows:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace TestDefine {

class Program {

static void Main(string[] args) {

Console.Write("Please enter a number: ");

int num = int.Parse(Console.ReadLine());

int sum = 0;

for (int i = 1; i <= num; i++) {

//---sum up all odd numbers---

if (i % 2 == 1) {

sum += i;

#if DEBUG

Console.WriteLine("i={0}, sum={1}", i, sum);

#elif NORMAL

Console.WriteLine("sum={0}", sum);

#else

Console.WriteLine(".");

#endif

}

}

Console.WriteLine(

"Sum of all odd numbers from 1 to {0} is {1}",

num, sum);

Console.ReadLine();

}

}

}

Figure 3-15 shows the different output when different symbols are defined. The top screen shows the output when the DEBUG symbol is defined. The middle screen shows the output when the NORMAL symbol is defined. The bottom screen shows the output when no symbol is defined.

Figure 315 The ifpreprocessor directive can also test for multiple conditions - фото 96

Figure 3-15

The #ifpreprocessor directive can also test for multiple conditions using the logical operators. Here are some examples:

#if (DEBUG || NORMAL) //---either DEBUG or NORMAL is defined---

#if (DEBUG && NORMAL) //---both DEBUG and NORMAL are defined---

#if (!DEBUG && NORMAL) //---DEBUG is not defined AND NORMAL is defined---

#warning and #error

The #warningpreprocessor directive lets you generate a warning from a specific location of your code. The following example shows how you can use it to display warning messages during compilation time.

for (int i = 1; i <= num; i++) {

//---sum up all odd numbers---

if (i % 2 == 1) {

sum += i;

#if DEBUG

#warning Debugging mode is on

Console.WriteLine("i={0}, sum={1}", i, sum);

#elif NORMAL

#warning Normal mode is on

Console.WriteLine("sum={0}", sum);

#else

#warning Default mode is on

Console.WriteLine(".");

#endif

}

}

Figure 3-16 shows the output when the DEBUGsymbol is defined using the /definecompiler option.

Figure 316 The errorpreprocessor directive lets you generate an error - фото 97

Figure 3-16

The #errorpreprocessor directive lets you generate an error. Consider the following example:

for (int i = 1; i <= num; i++) {

//---sum up all odd numbers---

if (i % 2 == 1) {

sum += i;

#if DEBUG

#warning Debugging mode is on

Console.WriteLine("i={0}, sum={1}", i, sum);

#elif NORMAL

#error This mode is obsolete.

Console.WriteLine("sum={0}", sum);

#else

#warning Default mode is on

Console.WriteLine(".");

#endif

}

}

Here, if the NORMALsymbol is defined, an error message is shown and the statement defined within the conditional directive is ignored. Figure 3-17 shows that when you define the NORMALsymbol, the error message is displayed and the compilation is aborted.

Figure 317 line The linepreprocessor directive lets you modify the - фото 98

Figure 3-17

#line

The #linepreprocessor directive lets you modify the compiler's line number and (optionally) the file name output for errors and warnings.

The #linepreprocessor directive is injected in the following example. The highlighted code indicates statements that will cause the debugger to issue warning messages:

1. using System;

2. using System.Collections.Generic;

3. using System.Linq;

4. using System.Text;

5.

6. namespace TestDefine

7. {

8. class Program

9. {

10. static void Main(string[] args)

11. {

12. #line 25

13. int i; //---treated as line 25---

14. char c; //---treated as line 26---

15. Console.WriteLine("Line 1"); //---treated as line 27---

16. #line hidden //---treated as line 28---

17. Console.WriteLine("Line 2"); //---treated as line 29---

18. Console.WriteLine("Line 3"); //---treated as line 30---

19. #line default

20. double d; //---treated as line 20---

21. Console.WriteLine("Line 4"); //---treated as line 21---

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

Интервал:

Закладка:

Сделать

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

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


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

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

x