The Nineth chapter of ". NET programming Pioneer C #" Configuration and scheduling (turn)

Source: Internet
Author: User
Tags definition bool comments constructor documentation visual studio
Programming nineth chapter Configuration and scheduling
In the previous chapter, you learned how to create a common language runtime (CLR) component and how to use it in a simple test application. While the CLR component is ready to load, you should still think about one of the following technologies:
。 Conditional compilation
。 Document comments
。 Version of Code

9.1-Piece compilation
Without the conditional compilation feature of the code, I can't go on working. Conditional compilation allows you to execute or include code based on certain criteria, such as a debug version, demo version, or retail (release) version of an application. Examples of code that can be included or executed for license code, screen protection, or any program that you produce.
In C #, there are two methods for conditional compilation:
。 Preprocessing usage
。 Condition Properties
9.1.1 Preprocessing usage
In C + +, the preprocessing steps are separate before the compiler starts compiling the code. In C #, preprocessing is simulated by the compiler itself-no preprocessing for separation. It's just conditional compilation.
Although the C # compiler does not support macros, it has the necessary functionality to exclude and include code based on the conditions defined by the symbol. The following subsections describe the various flags that are supported in C # and are similar to those seen in C + +.
。 Defining symbols
。 Exclude code by symbol
。 Cause errors and warnings
9.1.1.1 definition Symbol
You cannot use preprocessing with the C # compiler to create "define flag: Symbol: definition" macros, but you can still define symbols. Depending on whether certain symbols are defined, you can exclude or include code.
The first way to define a symbol is to use the #define标志 in a C # source file:
#define DEBUG
This defines the symbol debug, and the scope is within the file that it defines. Note that you must define a symbol before you can use another statement. For example, the following code snippet is not correct:

Using System;
#define DEBUG

The compiler will mark the above code as an error. You can also use the compiler to define symbols (for all files):
Csc/define:debug Mysymbols.cs
If you want to define multiple symbols with the compiler, just separate them with semicolons:
Csc/define:release;demoversion Mysymbols.cs
In C # source files, the definitions of these two symbols are divided into two lines #define flags.
Sometimes, you may want to cancel a symbol in the source file (for example, the source file for a larger project). You can use the #undef flag to cancel the definition:
#undef DEBUG
The #define的 define flag: Symbol: Definition rule also applies to #undef: its scope is within its own defined file and placed before any statement, such as a using statement.
This is all about the knowledge that you need to know to define symbols and to ungroup symbols with C # preprocessing. The following subsections describe how to conditionally compile code using symbols.

9.1.1.2 to include and exclude code based on symbols
The most important "if flag: symbol: Include code" method is intended to include and exclude code conditionally, depending on whether the symbol is defined. Listing 9.1 contains the source code that was already in place, but this time it was conditionally compiled according to the symbol.

Listing 9.1 uses #if flags to conditionally include code

1:using System;
2:
3:public class Squaresample
4: {
5:public void Calcsquare (int nsidelength, out int nsquared)
6: {
7:nsquared = Nsidelength * NSIDELENGTH;
8:}
9:
10:public int calcsquare (int nsidelength)
11: {
12:return nsidelength*nsidelength;
13:}
14:}
15:
16:class Squareapp
17: {
18:public static void Main ()
19: {
20:squaresample sq = new squaresample ();
21st:
22:int nsquared = 0;
23:
Calc_w_out_param: #if
25:sq. Calcsquare (out nsquared);
Num: #else
27:nsquared = sq. Calcsquare (15);
: #endif
29:console.writeline (Nsquared.tostring ());
30:}
31:}

Note that no symbols are defined in this source file. When compiling an application, define (or cancel) the symbol:
Csc/define:calc_w_out_param Square.cs
Depending on the symbol definition of "if flag: symbol: Include code", different calcsquare are invoked. The analog preprocessing mark used to evaluate the symbolic value is #if, #else和 #endif. They produce the same effect as C # 's corresponding if statement. You can also use the logic "and" (&&), logic, or (¦¦) and "No" (! )。 Examples of them are shown in Listing 9.2.

Listing 9.2 uses #elif to create multiple branches in the #if flag

1://#define DEBUG
2: #define Release
3: #define Demoversion
4:
5: #if DEBUG
6: #undef demoversion
7: #endif
8:
9:using System;
10:
11:class Demo
12: {
13:public static void Main ()
14: {
: #if DEBUG
16:console.writeline ("Debug version");
#elif Release &&! Demoversion
18:console.writeline ("Full release version");
: #else
20:console.writeline ("Demo version");
#endif
22:}
23:}

In this "If flag: symbol: Include code" example, all the symbols are defined in the C # source file. Note that the 6th line #undef the portion of the added statement. Because you do not compile the demo version of the debug code (optional), I am sure it will not be inadvertently defined by some people, and always cancel the definition of the demo version when debug is defined.
Then on line 15th to 21st, the preprocessing notation is used to include various code. Note the use of the #elif flag, which allows you to add multiple branches to the #if flag. The code uses the logical operator "&&" and non-operator "!" ”。 The logical operator "¦¦" may also be used, as well as equals and not equal to the operator.

9.1.1.3 causes errors and warns
Another possible use of the "Warning flag error Flag" Preprocessing flag is based on certain symbols (or not at all, if you decide so) to cause errors or warnings. The respective flags are #warning和 #error, and listing 9.3 shows how to use them in your code.
Listing 9.3 Using preprocessing flags to create compilation warnings and errors

1: #define DEBUG
2: #define Release
3: #define Demoversion
4:
5: #if demoversion &&! DEBUG
6: #warning You are building a demo version
7: #endif
8:
9: #if DEBUG && demoversion
#error cannot build a debug demo version
One: #endif
12:
13:using System;
14:
15:class Demo
16: {
17:public static void Main ()
18: {
19:console.writeline ("Demo application");
20:}
21:}

In this example, when you generate a version of demo that is not a debug version, a compile warning is issued (line 5th ~ 7th). When you attempt to generate a debug demo version, it causes an error that prevents the executable from being generated. In contrast to the previous example of just canceling the definition of annoying symbols, the code tells you that the "Warning sign error mark" Attempt to do the work is considered wrong. This is certainly a better approach.
9.1.1.4 Conditional Properties
C + + preprocessing may most often be used to define macros, which can solve a function call when a program is generated, but not solve any problem when another program is generated. Examples include assert and trace macros, which are evaluated for function calls when the debug symbol is defined, and when a release version is generated, the evaluation has no result.

When you learn that macros are not supported, you might guess that the conditional function has died out. Fortunately I can report that there is no such situation. You can use conditional attributes to include methods based on some of the defined symbols. :

[Conditional ("DEBUG")]
public void SomeMethod () {}

This method is added to the executable file only when the symbol debug is defined. and call it, just like
SomeMethod ();

When the method is not included, it is also declared by the compiler. Functionality is basically the same as using C + + conditional macros.
Before the example begins, I want to point out that the conditional method must have a return type of void and no other return type is allowed. However, you can pass any parameters you want to use.
The example in Listing 9.4 shows how to use conditional properties to regenerate the same functionality as a Trace macro with C + +. For simplicity, the results are output directly to the screen. You can also direct it to anywhere, including a file, as needed.

Listing 9.4 Using Conditional property implementation methods

1: #define DEBUG
2:
3:using System;
4:
5:class Info
6: {
7: [Conditional ("DEBUG")]
8:public static void Trace (String strmessage)
9: {
10:console.writeline (strmessage);
11:}
12:
[Conditional ("DEBUG")]
14:public static void Tracex (String strformat,params object[] list)
15: {
16:console.writeline (Strformat, list);
17:}
18:}
19:
20:class testconditional
21: {
22:public static void Main ()
23: {
24:info.trace ("cool!");
25:info.tracex ("{0} {1} {2}", "C", "U", 2001);
26:}
27:}

In the info class, there are two static methods, which are conditionally compiled according to the debug symbol: Trace, which receives a parameter, and Tracex receives n parameters. Trace is implemented directly when. However, Tracex implements a keyword that you have never seen before: params.
The params keyword allows you to specify a method parameter that actually receives any number of arguments. An omitted parameter similar to C + +. Note that it must be the last parameter of the method call, and you can only use it once in the argument list. After all, their limitations are extremely obvious.
The intent of using the params keyword is to have a trace method that receives a format string and countless permutation objects. Fortunately, there is also a WriteLine method that supports a format string and an array of objects (line 16th).
Which output the applet produces depends entirely on whether debug is defined or not. When the debug symbol is defined, the method is compiled and executed. If debug is not defined, calls to trace and Tracex disappear.
Conditional methods are a truly powerful means of adding conditional functionality to applications and components. With some tricks, you can generate conditional methods based on multiple symbols that are connected by logical "or" (¦¦) and Logical AND (&&). However, for these scenarios, I would like to recommend C # documents to you.

9.2 Documentation Comments in XML
One of the tasks that many programmers dislike at all is writing, including writing notes and writing documents. However, with C #, you'll find a good reason to change your old habits: You can generate documents automatically with code annotations.
The output produced by the compiler is the perfect XML. It can be used as input to component documentation and as a tool for displaying help and revealing details inside components. For example, Visual Studio 7 is one such tool.
This section is dedicated to explaining how you can best use the document features of C #. This example covers a wide range, so you can't have the excuse that it's too complex to understand how to add a document annotation. Documents are an extremely important part of the software, especially the documentation of components that are used by other developers.
In the following subsections, document annotations are used to illustrate the Requestwebpage class. I have explained in the following sections:
。 Describe a member
。 Add notes and Lists
。 Provide examples
。 Description parameters
。 Description Properties
。 Compiling documents


9.2.1 describes a member
The first step is to add a simple description to a member. You can do this with a label:
This is .....


Each document comment starts with a symbol "///" consisting of three backslashes. You can put the documentation comments before the members you want to describe:

Class to tear a webpage from a Webserver

public class Requestwebpage

Use and labels to add paragraphs to the description. Use a label to refer to another member that already has a comment.
Included in the class

Add a description that links to the Requestwebpage class. Note that the syntax for labels is XML syntax, which means that the label capitalization problem, and the label must be nested correctly.
When you add a document to a member, another interesting label is. It allows you to describe other topics that may be of great interest to the reader.

///

The previous example tells the reader that he may also want to check the document for the System.Net namespace. You must specify a fully qualified name for projects beyond the current scope.
As a promise, listing 9.5 contains all the examples of the document that is working in the Requestwebpage class. Take a look at how labels are used and how nesting produces documents for the component.

Listing 9.5 uses,,,, and tags to describe a member

1:using System;
2:using System.Net;
3:using System.IO;
4:using System.Text;
5:
6:///Class to tear a webpage from a Webserver
7:public class Requestwebpage
8: {
9:private const int buffer_size = 128;
10:
One:///m_strURL stores the URL of the webpage
12:private string m_strURL;
13:
///Requestwebpage () is the constructor for the class
:///when called without arguments.
16:public Requestwebpage ()
17: {
18:}
19:
///requestwebpage (String strurl) is the constructor for the class
///when called with a URL as parameter.
22:public requestwebpage (String strurl)
23: {
24:m_strurl = strURL;
25:}
26:
27:public string URL
28: {
29:get {return m_strurl;}
30:set {m_strurl = value;}
31:}
32:
///the GetContent (out string strcontent) method:
///Included in the class
:///Uses variable
///Used to retrieve the content of a webpage. The URL
Notoginseng:///of the webpage (includinghttp://) must already be
///stored in the private variable m_strURL.
///to does, call the constructor of the Requestwebpage
:///class, or set its property to the URL string.
41:///
42:///
43:///
44:///
45:///
46:///
47:///
48:///
49:
50:public bool GetContent (out string strcontent)
51: {
52:strcontent = "";
53://...
54:return true;
55:}
56:}

9.2.2 Add notes and lists
Labels are places that specify a large number of documents. By contrast, only a brief description of the members is specified.
You are not limited to providing only paragraph text (using labels). For example, you can include a list of bulleted (and finite even numbers) in the Remarks section:

///
Constructor
Or
///
///
///

This list has one item, and the item references two different constructor descriptions. You can add content to the list item as needed.
Another label that works well in the Notes section is. For example, you can use to reference and describe the arguments passed to the constructor:

Stores the URL from the parameter///in
The private variable.
Public Requestwebpage (String strurl)

In Listing 9.6, you can see that all of these and the preceding tabs are working.

Listing 9.6 Adds a note and bullet list to the document

1:using System;
2:using System.Net;
3:using System.IO;
4:using System.Text;
5:
6:///Class to tear a webpage from a Webserver
7:///The class Requestwebpage provides:
8:///Methods:
9:///
Ten:///constructor
One:///or
12:///
13:///
14:///
15:///
:///Properties:
17:///
18:///
19:///
20:///
21:///
22:///
23:///
24:public class Requestwebpage
25: {
26:private const int buffer_size = 128;
27:
///m_strURL Stores the URL of the webpage
29:private string m_strURL;
30:
///Requestwebpage () is the constructor for the class
///when called without arguments.
33:public Requestwebpage ()
34: {
35:}
36:
Notoginseng:///requestwebpage (String strurl) is the constructor for the class
///when called with a URL as parameter.
///Stores the URL from the parameter in
///: the private variable.
41:public requestwebpage (String strurl)
42: {
43:m_strurl = strURL;
44:}
45:
///Sets the value of.
All:///Returns the value of.
48:public string URL
49: {
50:get {return m_strurl;}
51:set {m_strurl = value;}
52:}
53:
///the GetContent (out string strcontent) method:
///Included in the class
A:///Uses variable
///Used to retrieve the content of a webpage. The URL
///of the webpage (includinghttp://) must already be
///stored in the private variable m_strURL.
///to did, call the constructor of the Requestwebpage
:///class, or set its to the URL string.
62:///
///retrieves the content of the webpage specified in
:///the property and hands it
:///parameter.
A:///the is implemented using:
67:///
In:///the method.
///: The method.
///the method
I:///the method
:///the method
Together:///the property and its
:///method
///the "method" for the
A:///object.
77:///
78:///
79:///
80:public bool GetContent (out string strcontent)
81: {
82:strcontent = "";
83://...
84:return true;
85:}
86:}

9.2.3 provides examples
The best way to illustrate the use of an object and method is to provide examples of good source code. So don't be surprised that a document annotation also has a label for declaring an example: and. The tag contains an entire example of the description and code, and the tag contains only the example code (surprisingly).
Listing 9.7 shows how to implement the code example. Examples included are used for two constructors. You have to provide examples of getcontent methods.

List. 7 Use examples to explain concepts

1:using System;
2:using System.Net;
3:using System.IO;
4:using System.Text;
5:
6:///Class to tear a webpage from a Webserver
7:///...
8:public class Requestwebpage
9: {
10:private const int buffer_size = 12


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.