"C # Advanced Programming Third Edition" The first section of the first chapter is released! ! !

xiaoxiao2021-03-06  41

Part 1: C # language

Chapter 1.NET architecture

Translation: Coofucoo

Chapter 1.NET architecture

Read this book You will find that this book is emphasized that the C # language should not be treated by the isolated, it must be considered with .NET Framework. The C # compiler is a specific goal with .NET, this means that the code written with C # must be supported on .NET Framework. In this way, there are two important inference for C #:

❑ c C # architecture and methodology reflect the fundamental methodology of .NET.

❑ In many cases, many dedicated language features of C # depends on .NET's feature or .NET basic class.

Due to this dependency, understand the architecture and methodology of .NET's architecture and methodology before starting C # programming. This is also the purpose of this chapter.

Let's take a look at what happens when all language (including C #) is compiled and runtime. Once we have a roughly understanding, we will learn more about Microsoft Intermediate Language (MSIL or Abbreviation IL), and all languages ​​on the NET will eventually be compiled into this assembly language. In particular, we will understand how IL, COMMON TYPE SYSTEM (CTS) and COMMON LANGUAGE SPECification (CLS) work together make the language below. Net can work together. We also have to discuss how Visual Basic and C are suitable for .NET.

After you have finished these, we will continue to learn about other features of .NET, including assemblies, namespaces, and .NET basic classes. Finally, we have to make a general understanding of the type of application that can be created like a C # developer.

1.1 C # and .NET relationship

Compared to other languages, C # is a new programming language, and the following two aspects reflect his importance:

❑ It is designed for Microsoft .NET Framework (a platform for developing, deploying, and executing distributed applications).

❑ It is a language based on modern object-oriented design method. When he is designed, the object-oriented principle has been significantly applied for more than 20 years, and Microsoft has absorbed all of these experienced language.

An important issue is to figure out that C # itself is a language. Although it is a design to generate code in the .NET environment, it is not part of .NET. There are also some features .NET support, but C # does not support, and may be more amazed, there are some features of the C # language .Net does not support! (For example, some operators overload)

However, because the C # language is used for .NET, it is important to understand the .NET Framework if we want to use C # to develop efficient software. Therefore, in this chapter, we will take some time to observe the .NET through the surface. Ok, let's get started!

1.2 Public language operation

The core of .NET Framework is a runtime execution environment, which is called the public language runtime (CLR) or .NET runtime. The code running under the control of the CLR is often referred to as a managed code.

However, all our source code (using C # or other languages) needs to be compiled before being executed by the CLR. This compilation requires two steps:

1. Compile the source code as an intermediate language (IL) code

2. Compile the intermediate language code as the code above the specific platform by the CLR

These two step compilation processes are very important because the existence of intermediate language (IL) is the key to numerous advantages of .NET. Ok, let's take a look at why. 1.2.1 Advantages of hosting code

The Microsoft Intermediate Language is shared with Java bytecode, and they are a simple low-level language (based on digital code, rather than text code), can be quickly translated into local machine code. The code has such a good design and general grammar is a significant advantage.

1.2.1.1 platform independence

First, this means that the same file containing byte code instructions can be deployed in any platform, and the last phase of the compilation process can be easily completed at runtime, so the code can run on a specific platform. In other words, the source code is compiled into an intermediate language allows us to get the .NET platform independent, which is the same as the Java platform, which is compiled as Java bytecode to obtain platform-independent.

You should notice that this platform-independent of .NET is currently theoretically, because when writing this book, only the .NET is fully implemented on the Windows platform. However, there is already a partially implemented .NET (see Mono project, one is working on .NET, for the establishment of the open source platform, please visit www.go-mono.com/)

1.2.1.2 Performance improvement

Although the front and Java have been compared, actually the intermediate language (IL) is more ambient than the Java bytecode. IL is always instant translation (called JIT compilation), but Java bytecodes are often interpretative. A disadvantage of interpreting compilation like Java is that during runtime, translate Java byte code to local executable code results in performance loss (here you do not include the newly joined Java platform, some specific Java platforms have been Realized JIT compilation).

It is not once to compile the entire application (then, the application is slower when the application is started), JIT is just a simple part of the code that will need to be used (just like his name, instant compilation). Once the code is completed, these code will be saved as the local executable result until the application exits. So, when this part of the code is called again, it is not necessary to compile again. Microsoft believes that the efficiency of this process is much higher than that compiles the entire application. Because the possibility that the application code that actually runs most of the application code is not large. With this JIT compiler, such a code will never be compiled.

This explains why we think that the hosted IL code is as fast as if you do this. However, this does not explain why Microsoft thinks we will improve performance. One reason for improvement in performance is that when the last compilation phase occurs at runtime, the JIT compiler has exactly knows the processor type that the program will run. This means that the compiler can optimize the final executable code to take advantage of any features and specific machine code instructions brought about a particular processor.

The traditional compiler also optimizes the code, but it is just an optimization that is independent of a specific processor that will run with the program. This is because the traditional compiler is compiled as a local execution code before the software is loaded. This means that the compiler does not know the processor type that the software will run, for example, is it running on the X86 compatible processor or on the alpha processor. For example, Visual Studio 6 is optimized for a normal Pentium processor, so this also means that the code it produces cannot utilize the hardware features of the Pentium III processor. Instead, JIT can be optimized in addition to the optimization work completed by Visual Studio 6, it is also possible to optimize the specific processor to be run.

1.2.1.3 The role of language interoperability IL is not only impartable to the platform, but it also promotes language interoperability. Simply put, you can compile the code of any language into IL, and this compiled code can interact with IL-compiled IL compiled into any other language.

Now you may want to know what language except C # can interact with .NET, is it? Ok, then let us briefly discuss how other languages ​​make themselves .net.

Visual Basic .NET

Upgrade from Visual Basic 6 to the latest Visual Basic.Net, Visual Basic has experienced a thorough transformation. From the date of development of Visual Basic 6 in recent years, it is not a language suitable for running .NET. For example, he is integrated with COM and is just to display the source code to the developer through the program process, so that a large number of post-code developers in the source code cannot be utilized. Not only this, Visual Basic 6 does not support realization, and the standard data type of Visual Basic 6 is also incompatible with .NET.

Now, Visual Basic 6 has been upgraded to a new Visual Basic .NET, and the language changes so know, so you'd better think of Visual Basic .NET as a new programming language. The already existing Visual Basic 6 code is now compiled as code as a Visual Basic .NET. If you want to transfer your previous Visual Basic 6 code to Visual Basic .NET, you must make huge modifications. But Visual Studio .NET (a new generation of .NET-based VS) can do most of these modifications for you. If you try to open the original Visual Basic 6 in Visual Studio .Net, Visual Studio .NET will upgrade the project for you, which means it will override the original Visual Basic 6 source code with Visual Basic .ne. Although the heavy work of this upgrade code has greatly reduced, you still have to check the new Visual Basic .NET code has been determined that it is indeed correctly, after all, such a conversion may not be perfect.

Another change after the upgrade is that Visual Basic .NET will not be compiled into a local execution code, the same opposite, and C #, he is compiled into IL. Maybe you still need to continue to write Visual Basic 6 code, maybe you do need this, you must develop in the original Visual Studio 6, and such code will completely ignore the .NET Framework.

Visual C .net

In order to adapt to Windows, Microsoft Visual C 6 has made a large specific expansion. Go to Visual C .NET, which is also extended to support .NET Framework. This means that the existing C source code can be compiled as a local executable code without the continued transaction. However, this also illustrates that such local code and .NET runtime are not related. If you want to make your C code on the .NET Framework, you need to add this line to your code.

#using

You can also pass a "/ CLR" parameter to the compiler, which can set you want to compile as a managed code, compile the source code into IL instead of local machine code. Interestingly, when compiling C as a managed code, the compiler compiles an IL containing an inline execution code. This means that you can mix managed types and unmanaged types in your C code. Host C code like this: Class MyClass

{

Define a normal C class, and the following code:

__GC Class Myclass

{

Will define a hosted class, just like you are in C # or Visual Basic .NET definitions. Hosting C code is better than C # code is that you don't have to use COM interaction function to directly call the non-hosting C class.

If you try to use a .NET on the managed type, the compiler is not supported, the reporter is incorrect (for example, template or more inheritance). Of course, you will also find that you need to use non-standard C features when you use the managed class (for example, the keyword "__gc" mentioned above).

Due to the freedom of C , C allows low-level pointer operations, the C compiler cannot generate code that can pass through the CLR memory type security test. If you pass through the CLR's memory type security test, you are important to your code, then you use other languages ​​to write your source code (such as C # or Visual Basic .NET).

Visual J # .NET

The latest language to join this big family is Visual J # .NET. Before the .NET Framework 1.1 is launched, if you want to use J #, you must go another download. But now, J # has been built into the .NET Framework. Because of this, J # users can now have all versatile advantages of Visual Studio .NET. Microsoft I hope most J users can see if they want to write programs under .NET, J # is the most convenient choice. Unlike those languages ​​running the environment with the Java runtime library, J # is the same as the .NET's underlying class library like .NET. This means that you can use J # to create an ASP.NET web application, Windows Forms, XMLWeb services, and all like C # and Visual Basic .NET can do.

Scripting language (scripting language)

Although it seems to be weakened due to the importance of .NET's income, they are still still use. On the other hand, JScript has now been upgraded to JScript .NET. We can now use JScript .NET to write ASP.NET programs, run JScript .NET like a compiler, rather than previous interpretation programs, and write a large number of JScript .NET code. With ASP.NET, there is no need to use scripting languages ​​on the service period web page. However, now VBA is still used to write the macro of Microsoft Office and Visual Studio.

COM and COM

From a technical saying, COM and COM are not .NET technology, because components based on both technologies cannot be compiled into IL (although it will be possible to some extent, if the original COM component is used C is written, then managed C can be utilized). However, because some characteristics of COM are not supported by .NET, it is still an important tool. Similarly, the COM component is still able to, .NET combined with the interoperability function of COM, allowing managed code to call COM components, and vice versa. (Chapter 29 will discuss this) However, in general, it is very convenient for most purposes, such words, you can use the .NET basic class and other managed code. 1.3 Near Intermediate Language

From the chapter above, we can see that Microsoft intermediate languages ​​are obviously playing a very important role in .NET Framework. As a C # developer, we have now understood that C # code will be compiled into IL before execution (it is true, C # is only compiled into managed code). In this way, the main characteristics of the observation of IL now have become very meaningful, because any language-oriented language also needs to support the main features of these IL.

Below is an important feature of these IL:

❑ Object-oriented and interface support

❑ 值 Value type and reference type difference is huge

❑ Strong data type

❑用 Use an exception to handle errors

❑ Property Application

Let us start at close range of property below the property.

1.3.1 Support for object-oriented and interface

The language independence of .NET has a certain actual limit. IL inevitable to achieve some specific programming methodology, this means that if there is a language ultimately compile into IL, then this language itself should be consistent with this methodology. Therefore, for IL, Microsoft selection is a classic object-oriented methodology that only supports single inheritance.

Readers who don't understand the object theory should refer to the following appendix A has obtained more information. At http://www.wrox.com you can get Appendix A.

In addition to the classic object-oriented methodology, IL also introduces the concept of an interface. The concept of this interface is COM for the first time in Windows. .NET interface and COM interface are different. However, .NET shared the interface idea of ​​COM, the interface provides a contract, and if the class must provide this interface method and property implementation method if you want to implement a given interface.

1.3.1.1 Object-Oriented and Language Interoperability

Now we have seen that if you work and program below .NET, you must comply with classic object-oriented methodology, and the code written must also be compiled into IL. But just these are not enough to provide language interoperability. After all, C and Java also abide by the same object-oriented specification, but they still can't be considered to be interoperable. We need to further understand the concept of language interoperability.

First, we need to consider the concept of our language interoperability. After all, COM allows components to be written in different languages ​​to cooperate together by calling each other. Is there any shortcomings? COM, through a binary standard, allowing components to instantiate other components and call their methods and properties without considering what language written in what these components are written. However, in order to achieve such purposes, each object must be instantiated by COM running and need to be accessed through an interface. Based on the thread model of the relational component, the memory space between the county is organized or the data or the data that run components or both will bring a lot of performance losses. In the extremely short case, the component resides in an executable, not a DLL file, which requires different processes to run them. It is important that components may need to communicate with each other, but they can only communicate when COM is running. Under COM, the components written in different languages ​​cannot communicate directly, or instantiate each other, these operations are only used as the medium. Not only these, the COM architecture is not allowed to achieve inheritance, so COM has lost many object-oriented programming. Another related question is that when you debug, you still need to debug these components written in different languages ​​separately. It is impossible to subtocate multiple languages ​​on the debugger. So what is the true meaning of the language interoperability is a class-written class that can be directly communicated directly with the class written in another language. special:

❑ 用 Class written in a language can inherit the class written by another language

❑ A class can contain an instance of another class, not what is the language of two classes?

❑Reworthy objects can directly call objects of another language

❑ 对 Object (or reference) can pass between methods

❑ We can use step-by-step debugging when calling a method between different languages, even if this means that single-step debugging is made in the source code of different languages.

This is an absolute ambitious plan, but amazing is that .NET and IL have reached this goal. When the call between the single-step debug method is used in the debugger, it is not a CLR, but the Visual Studio .NET IDE provides us with this convenient feature.

1.3.2 value type and reference type

Like any other programming language, IL provides many pre-defined raw data types. However, the distinctive difference type and application type are also an important feature of IL. The value type is those types that directly store data values, and the reference type just stores the address of the memory unit where the data value is located. With this address, we can find the appropriate data.

In C terms, similar to the reference type is a pointer, and in Visual Basic, the object is most similar to the reference type here, and the object in Visual Basic is always accessed by reference. The IL also made detailed specifications because of the storage citation type, which is always stored in memory called hosted stacks, and the variable of the opposite value is usually stored in the stack (although a value type is defined in a reference type. However, they are still stored in the pile of inline). We will discuss stacks and piles in Chapter 3, and how they work.

1.3.3 strong data type

An important feature of IL is that it is based on strong data type exception check. That is to say that all variables in IL must be clear to indicate specific data types (eg, the Variant data types allowed in Visual Basic and scripting languages ​​are not existing). In particular, IL does not allow operations that cause ambiguity data.

For example, because Visual Basic 6 can automate type conversion, Visual Basic 6 developers can pass the variables until too much consider their type. C developers are used to convert pointers in different types. Performing such an operation can greatly improve performance, but this also destroyed the type of security. Therefore, this is only allowed to be allowed in certain languages ​​that need to be compiled as a managed code. It is indeed this, the pointer (relative to the reference) is only allowed in the labeled C # code block, and the pointer is not used in Visual Basic (although it is allowed in managed C ). The use of the pointer in the code will result in failure in the type security check execution in the CLR. You should notice that there are still some .NET still allows you to relax in the type check, such as Visual Basic .NET, but it is only the compiler to determine such types to ensure the type security of the background IL.

Although mandatory types of security checks may result in performance loss, in many cases, the benefits of various services provided by .NET far exceed the performance losses caused by type security checks. These services include:

❑ Language interoperability

❑ Garbage collector

❑ Security

❑ Application domain

Let us let us understand why strong data types are particularly important.

1.3.3.1 Importance of strong data types on language interoperability

If a class is a class that is derived, or if you want to include other classes, he needs to know the data type used by other classes. This is why the strong data type is such an important reason. Indeed, in the past is the detailed specification of this data type information, always hinders the mutual inheritance between languages, and achieving interoperability. This type of information is not simple in the standard executable or DLL file.

Assuming a method for a class of a Visual Basic .NET defines a return value is a "integer" -Visual Basic .NET type of standard data type. But C # does not have a data type of this name. Obviously, if the compiler knows how to make a constant map of Visual Basic .NET to C # already defined some type, we can inherit, call methods, call methods, and return values ​​in Visual Basic .NET. .

General type system

The problem of this data type. Net is solved by the Common Type System (General Type System, CTS). The CTS defines some predefined data types that can be used in IL, so all the language that is hoped to run with the .NET Framework, which needs to be generated on these types of code.

Considering the example of our just mention, the integer data type of Visual Basic .NET is actually a 32-bit band symbol integer, which is completely consistent with the data type INT32 in IL. So this is the data type of IL code. Because C # also knows this data type, the previous problem has been solved. In the source code, the keyword corresponding to the INT32 is int, so it only needs to simply make a conversion, convert the return type of the Visual Basic .NET method to INT.

CTS is not only the basic data type, but he also defines a rich type hierarchy, which contains a defined point, and other languages ​​can define their own types on this. The hierarchy of the Common Type System reflects IL's single inheritance object-oriented methodology. As shown in Figure 1-1:

Picture 1-1

The table below is used to illustrate the types mentioned in the above.

Types of

Meaninglessness

Types of

Base class, any type is inherited in him

Value type

Base class, any value type is inherited in him

Reference type

Access by reference, and stored in the stack

Built-in value type

Including most standard basic types, used to represent numbers, Boolean, character enumeration types

Collection of enumerated values

User definition value type

In the source code definition and save the data type of the value type. In the C # language, all structures are this

Interface Type

interface

Pointer type

pointer

Self-description type

To provide your garbage collector, you can use the benefits of the garbage collector, such a type is the type of self-description (see the next section)

Array

Type of data containing a batch of objects

Class type

In addition to self-description types other than arrays

Delegate

Designed to save applications for methods

User definition reference type

Define in the source code and saved as a data type of the reference type. In the C # language, all classes are this

Package value type

Type the temporary packaging value in one reference, this value type can also be stored in the heap

We don't listen to all built-in value types here because we will discuss them in detail in the second chapter. In C #, each predefined type will be mapped to the built-in type in the corresponding IL. The same is true in Visual Basic .NET.

Public language norm

Common Language Specification (CLS) is accommodated with CTS to ensure language interoperability. CLS is a minimum standard collection, all compilers that run the platform as the target of the target. Because IL is a rich language, many compilers have the authors like to implement a subset of the functional restrictions provided by IL and CTS. This way, as long as the compiler supports all the definitions supported by the CLS.

Tip: You can write code that is incompatible with CLS. However, if you do this, the compiled IL code cannot guarantee that the language interoperability is fully met.

For example, let's take a look at an example of writing about letters. IL is case sensitive. Developer developers in case sensitive developers using this case-sensitive flexibility to name them. However, Visual Basic .NET is not case sensitive. The work of CLS is to make CLS compatible code understand that they can't use any two names that are only different in case. In this way, Visual Basic .NET can work with any CLS compatible code.

This example shows that CLS has two ways of working. First, each compiler function does not have to be strong enough to meet all the characteristics of .NET, which encourages other compiler vendors to join their language to this big family. Second, he also provides such a guarantee: if you limit your class to meet the compatibility of CLS, then other compatible languages ​​written code can use your class.

The advantage of this method is that the limitations using CLS compatibility features are only applicable to public or protected members of public categories and classes. For the implementation of private members in your class, you can write any non-CLS compatible code because the code of other assemblies is not accessible anyway.

Here we don't need detailed discussion of the details of the CLS specification. In general, since the non-CLS compatibility characteristics in C # are small, CLS is not affected by your C # code.

1.3.3.2 Garbage collection

The garbage collector is a .NET's memory management method, especially for this issue of how to recycle the memory of the application, the garbage collector provides a good solution. So far, two technologies have been shown on how to release process dynamic applications, two technologies have appeared on the Windows platform.

❑ Let the application code you can manually implement memory release

❑ Let the object to call the number

Let the application code are responsible for releasing memory is low, but high-performance languages, such as C . This method is efficient, and his advantage is that the resources will be released immediately once it is no longer necessary (in general). However, he also brought a lot of shortcomings, thereby triggeting the defects very frequent. The memory of the code application should certainly know the system when they are no longer needed. However, it is very easy to ignore this, never lead to memory leakage. Although the modern development environment does provide tools that help detect memory leaks, because such issues are only discovered when the Windows refuses to approve the process, it is still difficult to capture. From this point of view, due to the demand for memory, the entire computer will gradually become quite slow.

COM uses the method of maintaining the application count to solve this problem. The method of COM is that each COM component maintains a counter, which saves how many client applications are currently available. When the value of this counter drops to zero, the component will destroy himself and release the relevant memory and resources. But this solution when the problem is still in time to inform the components in a timely manner. They have already used the references. As long as there is a client to destroy yourself in time, the component will stay in memory. However, from some extent, this memory leak may be more serious than C memory leaks, because the COM object will save in its own process and will never be deleted by the system (at least for C memory leakage problem, the system can be All memory resources are retracted while the process is stopped.

Now, .NET runtime is changed to rely on the garbage collector to recycle resources. Garbage collector is a program that specializes in organizing memory. The method is to assign all dynamic applications to the pile (this is the same for all languages, but in .NET, CLRs should be used separately to manage themselves for use for .NET applications). The situation is often the case, when .NET detects that the hosted stack assigned to a process has been met, he will call the garbage collector. The garbage collector scans the variables in your code, check the reference to the object on the hosted stack, to determine which one is still in use - that is, which objects have a reference to themselves. Any object that has not been cited without your code will be considered no longer need to be used, so they will be removed. Java also has a similar garbage collector.

The garbage collector in .NET itself is designed to adapt to the work of the process. The principle is: Unless you copy an already existing reference, you can't set a reference for the existing object, and IL is type security. Here is the meaning that if there is a reference to the object, then we have enough information to clearly determine the type of object.

The garbage collection mechanism is not suitable for use in language like non-managed C , for example, C allows the pointer to free conversion in different types.

An important feature of the garbage collection mechanism is that its operating time is uncertain. In other words, you can't guarantee when the garbage collector is called, when the CLR feels that it is necessary to call it, he will be called (unless you know it clearly). Although you can also call the garbage collector directly in your code without considering these processes.

1.3.3.3 Security

Because .NET can provide code-based security mechanisms, .NET is better than Windows in security mechanisms, let alone Windows only provide role-based security.

Role-based security mechanism is based on the account running in the identification process, in other words, who has and run this process? On the other hand, the security of the delivery code is based on how the identification code itself is executed and its own credibility is based on how much credibility is. Fortunately, IL provides a powerful type of security mechanism, and CLR can pre-check the code security before code run to determine the required security license. .NET also provides a mechanism, and the code can pre-indicate what it needs to run. The importance of code-based security is that she can reduce the risk of codes that are unknown in operation (such as you are in the German code). For example, even the code is running under the administrator account, code-based security can still point out that this code still should not be allowed to perform some administrators should usually be allowed, such as read or write environment variables, read or Write an registry or access .NET reflection characteristics.

Detailed questions in security We will discuss 14 chapters.

1.3.3.4 Application Domain

The application domain is an important reform of .NET. Running applications require both each other and need to communicate with each other, the application domain is design to solve such a tricky problem. The classic case in this regard is a web application server while needing a number of requests for many visits. Therefore, the application server may run a lot of different instances in order to give different request services.

There are two ways to solve this problem before .NET appears. One is to allow these instances to share the same process, but this may result in an instance failure that causes the entire web server to close. Another method is to isolate these instances in different processes, but this also brings a decrease in performance.

So far, we are isolated by running the code in different processes. When you start an application, he is running in a process environment. The Windows system is isolated from each other through the address space. The specific method is that each process has 4GB virtual memory to store his own data and executable code (4GB for 32-bit systems, more than 64-bit systems). Windows indirectly expands the size of the virtual memory by building a virtual memory with the actual physical memory or disk space. Each process has a different mapping, and the actual memory mapping of the virtual address space block is not overlapped with each other (as shown in Figure 1-2).

Figure 1-2

In general, the process can only access physical memory through specific addresses in virtual memory, and the process cannot directly access physical memory. This is impossible to have a process that you want to access other processes. This also guarantees that any code with error behavior cannot damage anything other than the address space (note, this security measures are not like on Windows NT / 2000 / XP / 2003 platform. That thoroughly, it is theoretically there is a possibility that the application writes inappropriate memory and causes the possibility of Windows crash).

The purpose of introducing a process is not only an example used to isolate the running code. In the Windows NT / 2000 / XP / 2003 system, the process or security permissions and licensed can be allocated. Every process has its own security logo, this logo tells Windows what kind of operation is to allow this process to be performed.

Although the process has great help to security, its maximum disadvantage is to bring a loss of performance. Usually, many processes need to work together, so they need to communicate with each other. A obvious example is that there is a process that needs to call a COM component, and this COM component is also executable, so the COM component itself needs to run in its own process. There will be similar situations in COM. Since the process does not share memory, a complex job is to copy data between the processes. The result of doing this is to bring huge performance losses. If you want the component to work together, you have to use a DLL-based component technology, so all the code will run in the same address space - of course, the risk is that if One of the components runs wrong, then all programs in this process are turned off. The purpose of the design application domain is to solve the problem of sharing data between processes without loss of performance. The specific approach is that every process is broken down into many application domains. Each application domain corresponds to a hidden separate application, each executed thread runs in a specific application domain (as shown in Figure 1-3).

Figure 1-3

If different executable code is running in the same process space, it is clear that they can easily share data because they can directly access each other's data. Although theoretically, the CLR will check each running code to ensure that the code does not exceed the information that the code does not exceed the area you own. At first glance, it seems impossible, after all, if you don't actually run the code, how do you know how the code is running?

In fact, because IL has a powerful type security mechanism, this is possible. In most cases, unless code uses unsafe features, such as pointers, the data type ensures that memory will not be accessed. For example, the .NET array type performs a boundary check to ensure that any off -ral array operation is not allowed. If a running application does need to communicate or share data with another running application with different application domains, then it must be implemented by calling the remote service of the .NET.

This verification code is to ensure that the code cannot exceed the mechanism of application domain access data, called memory type security (different from the external remote call mechanism). This type of security code that is in a different application domain in a process is safe to run without interference.

1.3.3.5 Error by abnormal treatment

Like the exception handling mechanism used by Java and C , .NET Framework is also designed to adopt this convenient error-based error handling mechanism. C developers should notice that due to the same IL has a powerful input system, the use of exceptions in the same manner in IL and does not bring performance loss. .NET and C # also support a number of Finally blocks expected by many C developers.

We will discuss abnormalities in detail in Chapter 11. Simply put, the method of exception handling is specifying a piece of code as an exception handling routine to handle special exceptions, each piece of code can handle a specific error condition (for example, a file is not found, or some operations Refuse to execute). This particular error condition can be customized according to your needs, you can set a narrow condition can also be very wide. The abnormality processing architecture ensures that once there is an error condition, the program will immediately skip to execute the code block in the exception handling routine.

The abnormal processing architecture also provides a convenient way, you can pass an object that contains clear exception information to an exception handling routine. This object may contain a particular message of the user and the specific code to detect an exception.

When an abnormality occurs, most exception handling architecture, including program flow control, is processed by advanced language (e.g., C #, Visual Basic .NET, C ), not supported by any particular IL command. For example, C # utilizes code block try {}, catch {}, and finally {} (see Chapter 11). However, .NET also does provide an infrastructure that allows all compilers that run the platform with .NET to support exception handling. In particular, .NET provides a collection of .NET classes to specifically represent abnormalities, and language interoperability allows exception handling code processing throwing exception objects, regardless of whether the code is written in writing. This language-independent is that the exception handling mechanism of C and Java cannot be implemented, but there is a certain embodiment of the incorrect handling mechanism of COM, which includes returning the error code from the method and transmitting the error object. The consistency of remained abnormal processing in different languages ​​is a vital part of multilingual development.

1.3.3.6 Use of attributes

Developers who write COM components with C must be familiar with this feature (by them using Microsoft's Com Interface Definition Language [Idl]). Attribute initial intent is to provide additional information related to certain programs to the compiler.

The attribute is supported by .NET, so now C , C #, and Visual Basic .NET are also supported. However, .NET's properties have innovative, that is, it provides a mechanism that allows you to define your own properties in your source code. These user-defined properties will be placed in the metadata corresponding to the data type or method. These metadata can be used for the preparation of documents, they can use the reflection technology to implement attribute-based execution design tasks. In addition, as in the principle of .NET language independent, it can be read in another language in the source code and read it in another language.

We will discuss attributes in Chapter 10.

1.4 assembly

A assembly is a logical unit that contains code compiled by .NET Framework. Here we don't want too much attention to the details of the assembly, because in Chapter 13, we will discuss in detail, but here summarize his points.

The assembly is completely self-description, and is a logical unit instead of physical, which means that he can store in not only one file (actually the dynamic assembly is stored in memory, not the file in). If an assembly is stored in multiple files, there will be a primary file containing the primary entry point and describes other files in the program.

It should be noted that the structure of their assembly is the same for executable code and library code. The only difference between them is that the program set of executable code contains a primary program export point, and the library code is not in the program set.

An important feature of the assembly allows it to include the types and method metadata defined in the corresponding code. However, an assembly also contains some description assemblies themselves. These include program collection data called an assembly list, which can be used to check the version information and integrity of the assembly.

Note: ILDASM, a Windows-based usage tool that can be used to check the contents of the assembly, including the list of assemblies, and metadata. We will discuss ILDASM in Chapter 13.

In fact, the program set contains the program's metadata means that the application or other assembly is called other code, with the information described in the assembly, there is no need to query the registry or other data source for how to use the assembly. . Relative to the old COM practice, this practice is a significant breakthrough. In previous old methods, the GUIDs and excuses of the components must be obtained from the registry, and in some cases, the details of the methods and properties need to be read from the type library. Disperse data in up to 3 locations, means that some things have a bad risk, thus preventing other software successfully using this component. By using the assembly, because all metadata is stored with the program's executable instruction, there is no such risk. Note that even if the program is dispersed in a different file, the synchronization data does not have problems. This is because the file containing the primary entry point of the assembly also stores details, hashes, and contents of other files, which means that if one of the files are replaced, or if it is damaged in any way, it will be Detected and the program rally refused to load.

There are two types, private assemblies and shared assemblies

1.4.1 private assembly

Private assemblies are the simplest types in the program. They came with the software in the software and were only used by the software. Under normal circumstances, this is the case. You are writing a application consisting of a user and several class libraries, and the code in the class library You just want this application to use.

The system guarantees that the private assembly will not be used by other software, as the application can only load the private assembly with the primary executable in the same directory or its subdirectories.

Since we generally believe that commercial software will always be installed in his own directory, this is to say that there is no package that has been overwritten, modified or applied to other packages other than the application outside of the package. Therefore, the assembly can only be used by the package you have, so you have more control rights for what software. Therefore, there is no need to take safety precautions, and there will be no other commercial software to override your assembly with some new versions (except for software designed to perform malicious damage). Of course, there is no conflict in the name. If your private assembly class and other people's private assembly is not tight, because any application can only use its own private assembly.

Because a private assembly is completely included, it is very simple to configure their process. In deployment, you only need to simply simply enter the specific directory of the application file directory system (no registration registration item). This process is called "zero impact installation" (or Xcopy installation, or we say green installation).

1.4.2 Sharing assembly

Sharing assemblies are specified as a public library that can be used by any application. Because any software can access the shared assembly. It is necessary to take some protection measures to avoid the following risks:

❑ Name conflict, other company sharing assemblies have the same name and your own shared assembly has the same name. This is a serious problem because the client code has theoretically access two assemblies at the same time.

❑ There is a possibility that a program that has a basic version of the same assembly of different versions, and the new version may not be compatible with some already existing client code.

The solution to these issues is to place the shared assembly in a specific catalog sub-tree in the file system, known as Global Assembly Cache (GAC). Unlike private assemblies, it is not possible to copy the shared assembly to the application's directory, which needs to be dedicated to the buffer. This process can be done with many .NET tools, including specific inspections for assemblies, including a small directory hierarchy in the assembly buffer to ensure assembly integrity.

In order to eliminate the possibility of the name conflict, the shared assembly does not give a name based on private key encryption method (private assembly only needs to specify the name of its primary file as its name). This name is called "strong name" to ensure unique, and each reference to the shared assembly must provide this name. The problem that the assembly may be overwritten by allowing the same assembly that allows both different versions of the two versions to solve it in the assembly list,

1.4.3 reflection

Because the program is stored in metadata, including all the types of all types and these types of members are defined in the assembly, so they can access metadata. All of this will be discussed in Chapter 10. This is a technique that is likely to be reflected, indicating that the hosted code can detect other managed code even detect itself, the information that has been determined. Reflection is often used to obtain details of the attribute, of course, you can also use reflection techniques for other purposes, such as by indirectly implementing classes or calling methods by providing the names of the class or method in a string. Through this method you can decide to installize the class or the method you need to call at runtime, without the need to be determined before the program is compiled.

1.5 .NET Framework class library

At least from one developer's point of view, a biggest advantage of writing hosting code is that you can use the .NET Basic Library.

The .NET basic class is a collection of a lot of hosted codes that have been prepared, almost all work that can be done with Windows APIs can be done. These classes also follow the object models used in IL, based on single-successive object model. This is to say that you can instantiate any .NET basic class, or you can derive your own class from it.

A huge advantage of .NET basic class library is to use it very convenient. For example, if you want to start a thread, you can call the Start () method of the Thread class directly. If you want to destroy a TextBox, you need to design the enabled property of the TextBox object to false. Although Visual Basic and Java developers are familiar with this convenient class library, this has brought great relief for C developers. After all, they have been using getDibits (), registerWndClassex () And the API function such as ISEquali ID, and there is a lot of Windows Handles to be delivered.

On the other hand, C developers can always easily access the entire Windows API, and Visual Basic 6 and Java developers will receive a lot of restrictions through the basic functions of accessing the operating system through their own language. The innovation of the .NET basic class library is that it combines the convenience of the Visual Basic and Java class libraries and overwrites the entire Windows API feature. Of course, there are still some Windows features that we cannot get through the use of the basic class library, you must use the API function to be implemented, however, those who are not available are some special features. For daily applications, the base class library is already enough. If you really need to call the API function, no matter if you are using C #, C , or Visual Basic .NET, .NET also provides so-called "Platform- Invoke" to ensure that the data type is converted correctly, so this call There is no difficulty in calling the function directly in C .

Note: WinCV, a Windows utility that can be used to explore class, structures, interfaces, and enumeration types in the underlying class library. We will discuss WinCV in Chapter 12.

Although the third chapter is used in the topic, it is used to introduce the theme of the basic class library, but in fact, when we complete the syntax of the C # language, the main task of this book is to teach you how to use .NET basic class A variety of classes in the library. This is a very broad basic class library! As a rough introduction, .NET's basic class library includes: ❑ IL provides core features (including, basic data types and CTS, see Chapter 3)

❑ WINDOWS GUI support and control (see Chapter 19)

❑ Web Forms (ASP.NET, discussed in Chapter 25 and 2)

❑ Data Access (ADO.NET, Chapter 21 and 22)

❑ Directory Access (see Chapter 24)

❑ File system and registry access (see Chapter 30)

❑ Network and web tour (see Chapter 31)

❑ .net attributes and reflections (see Chapter 10)

❑ Access Windows operating system (environment variables, see Chapter 14)

❑ COM interoperability (see chapter 28 and 29)

With an instructions, most of the code in the .NET underlying library is actually written in C # according to Microsoft's source files!

1.5.1 namespace

Namespace is a way to conflict between .NET cancellation classes and classes. He is used to avoid the following: You define a class that represents a consumer, and gives her a name called Customer, and there is another person to do this, which causes a conflict (imagine, there are many Consumers' business).

The namespace is just a set of data types, but the data type in the namespace automatically adds the namespace name before the name. And the namespace can be nested to each other. For example, most .NET base classes for general purpose are placed in a namespace called System. Basic class Array is in this namespace, so the full name of the array is System.Array.

.NET requires all data types to be defined in the namespace, for example, you can put your Customer class in a namespace called YourCompanyName. This is the full name of this class is "YourCompanyName.customer".

Note: If no namespace clearly provides, the defined type will be added to a global namespace without a name.

Microsoft suggests that for most situations, you should specify a namespace name of at least two nesting structures: The first referring to your company name, the second use to refer to the name of the technology or package existing For example, YourCompanyName.salesservices.customer. This ensures that the class of your application will not be named in most situations.

We will learn more about the namespace in more detail on Chapter 2.

1.6 Create a .NET application with C #

C # Of course, can be used to create a console application, a application that has only text running under the DOS window. You may use the console application when you test the class library, or use it when you create a UNIX or Linux daemon process. However, in more case you will create some applications that use more .NET technology with C #. In this section, we will take a general understanding of the C # which different types of applications can be created.

1.6.1 Creating an ASP.NET application

Active Server Pages (ASP) is Microsoft used to create a Web with dynamic content. An ASP page is basically a file that adds a large block running on the server-side VBScript or JavaScript code in HTML. When a client beacker requests an ASP page, the web server handles the server-side code and sends together with the HTML section to the client. Typically, these scripts are queried from the database and marked these data with HTML. For customers, ASP is an easy way to create an audio-based application. However, ASP does not have no shortcomings. First, the ASP page is slower because the server-side code is interpreted, not compiled. Second, the ASP file is difficult to maintain because they are unable structure, the server-side ASP code is completely mixed with ordinary HTML code. Third, sometimes developing ASP is also difficult because ASP supports rare to error handling and type checks.

Special, if you want to use VBScript to implement an error with VBScript in your page, you must use the ON Error Resume next to declare, and check Check Err.Number to determine whether the call to each component is normal.

ASP.NET is a new version of ASP and amended many questions. ASP.NET is not to replace the ASP. Instead, the ASP.NET page can exist on the same server with the original ASP application. Of course, you can write ASP.NET applications with C #.

We will explore the key features of ASP.NET. If you want to get more details, please refer to Chapter 25 to 27.

1.6.1.1 Features of ASP.NET

First, it is also the most important, the ASP.NET page is structured. That is to say, each page is a valid class inherited from .NET System.Web.ui.page, and you can override some methods, these methods will call throughout the page (you can think of these methods) ONApplication_Start and OnSession_Start events like it were similar to the ONApplication_Start events under the ASP. Because you can directly place the page directly in the event handler, the ASP.NET page is easy to understand.

Another advantage of the ASP.NET page is that you can create it with Visual Studio .NET, you can also create the commercial logic and data access components used here on the ASP.NET page with the same development environment. A Visual Studio .NET project or solution contains all files associated with an application. Moreover, you can also debug your ASP page in this editor, which is much better than the original Visual InterDev. Configuring the web server for InterDev and engineering to support them to debug a headache.

The clearest thing is that the post-code characteristics of ASP.NET allow you to further structure your method. ASP.NET allows you to isolate the server-side features on page code, individually in a class, this class will be compiled into a DLL file, and this DLL will be placed in the lower-level directory of the HTML section. The top of the page does not have a back code indication to connect the file and its DLL. When the hook is requested, the web server will initiate the corresponding events in the DLL file generated by the rear code generated by the page.

Finally, but it is also important, the increase in performance in ASP.NET is remarkable. Comparing classic ASP pages are interpreted, each request is interpreted, the web server caches the compiled ASP.NET page. This means that the request for the ASP.NET page will be much more faster than before.

ASP.NET also makes it easy to write an audio-based form, which you can use in your intranet. Traditional form-based applications provide a feature-rich user interface (rich client), but it is difficult to maintain them because of these user interface programs on different machines. For this reason, when people need a powerful user interface, people need to provide users with a wide range of support, people rely on form-based applications. However, with the arrival of IE5 and Navigator 6, the advantages of form-based applications are increasingly not obvious. IE 5 is consistent with DHTML and fully sound support, allowing programmers to create web-based applications that are identical to the original rich client environment. Of course, such an application is necessary and standard in IE, but Navigator is not supported. In many industrial conditions, standardization is now normal.

1.6.1.2 Web Forms

In order to make the establishment web page easier, Visual Studio .NET provides Web Forms. They allow you to create an ASP.NET page with a way to create a Visual Basic 6 or C Builder window. The corresponding code will appear in the form by dragging a Toolbox space in the form. Finally, you only need to write programs for events in each space. When you use a C # to create a web form, you are actually creating a C # class inherited from the Page base class, and an ASP.NET page specifies that this class is its post code. Of course, you create a web form does not have to use C #, you can also use Visual Basic .NET or other .NET language.

In the past, difficulties in developing web applications have made many teams don't like to develop web applications. If you want to successfully develop web applications, you must master a lot of different technologies, such as VBScript, ASP, DHTML, JavaScript, and more. By applying the concept of the form to the web page, the Web makes web development quite simple.

WEB control

The controls used in the web form are different from the ActiveX control. They are some XML tags in the ASP.NET namespace. When requested a page, the web jammer dynamically converts it to HTML and client scripts. Surprisingly, the web server can have several ways to perform the control of the server, and make corresponding transformations depending on the request of the requested visitors. This means that it is very simple to write a general user interface for the web page, and don't worry about your page, you will run on what kind of viewer, because Web considers it for you.

You can use C # or Visual Basic .NET to expand your web form toolbox. Building a new server-side control thing is very simple, implement .NET's System.Web.ui.WebControls.WebControl class is OK.

1.6.1.3 XML Web Service

Today, the HTML page occupies most applications in the World Wide Web. However, there is a way to communicate with each other in the Web of the device via an XML computer. In the future, the computer can use Web and XML to exchange information rather than adopting dedicated lines and proprietary formats, such as Electronic Data Interchange (EDI). The XML Web service is designed to serve the service Web, and the remote computer can provide dynamic information and analyze and reformat it before it is finally displayed. XML Web Services provides a simple way to provide information between computers in XML.

Technically, the XML web service on .NET is an ASP.NET page that returns XML instead of HTML to the client. Such a page contains a DLL that is derived from the back code from the Web Service class. Visual Studio .NET IDE provides an engine that simplifies web services development. One organization mainly has two reasons to use XML Web services. The first reason is that the XML Web service is dependent on HTTP, and the XML Web service can utilize existing networks as a medium for information transmission. Another reason is that the data format XML used by the XML Web service is self-description, non-special, platform independent.

1.6.2 Creating Windows Forms

Although C # and .NET is ideal for developing web development, they still provide good support for the development of so-called fat client or client applications, which must be installed on the end user's machine and execute. These features are provided by Windows Forms.

For those forms similar to Visual Basic 6, under .NET is Windows Form. To design a graphical window interface, you only need to drag the control from the toolbox to Windows Form. To determine the behavior of the window, you can write event handler for controls in the Form. A Windows Form project will be compiled into an executable, but this program must be installed on the end user's computer to run this program. Like other .NET project types, Visual Basic .NET and C # can create a Windows Form project. We will introduce Windows Form in detail in Chapter 19.

Windows control

Although Web Forms and Windows Forms development methods are the same, but you create the controls they use are different. Web Forms is created using a web control, while Windows Forms uses a Windows control.

Windows Control is more like ActiveX Control. When a Windows Control is implemented, he is compiled into a DLL and must be installed on a machine that is installed. In fact, .NET SDK provides a tool that can be created for ActiveX Control, so ActiveX Control can be used on Windows Forms. Like Web Controls, create a Windows Control also inherited from a specific class system.windows. Forms.control.

1.6.3 Windows service

A Windows Service is a program that is designed to run in the background of Windows NT / 2000 / XP / 2003 (excluding Windows 9x). If you want to create a program, this program needs to run continuously, at any time, the event that occurs, does not require the user to manually run the program, then this program is Windows Service. A good example is the World Wide Web Service program on the web server, which is used to listen to the service from the client web request.

Establishing Windows Service in C # is very simple. The system.serviceProcess Namespace of the .NET Framework's basic class library provides a lot of model files for processing related to the service. In addition, Visual Studio .NET allows you to create a C # Windows Service project, which is a method of creating basic Windows Service as a source code as a source code. We will introduce how to write Windows Services with C # in Chapter 32.

1.7 C # role in .NET Enterprise Architecture

The C # program is running requires support for .NET runtime, but when .NET runs to install, popularize, especially most household computers, may also need a few years. During this time, installing C # applications may mean that you also need to install .NET reissue components. Because of this, we will usually see that many C # applications will first be applied to an enterprise environment. In fact, C # provides a good opportunity for organizations that are interested in establishing robust, N-layer client-server applications. When combined with ADO.NET, C # has fast and regular access to the database, such as SQL Server and Oracle database. The Dataset returned to the database can be easily operated with the ADO.NET object model, and can automatically convert it to XML to facilitate transfer in office internet.

Once the new project database plan has been determined, C # provides an excellent medium to implement data access object layer, each providing a method of inserting, updating, and deleting different database tables.

Because it is the first component-based C language, C # is also ideal for implementing the business object layer. C # The complexity of the internal components of the intermediate layer is encapsulated so that the developer can set the time to focus the energy to bond their data access objects in the method, so that their methods can be more exact organization. Business logic. And by attribute, C # business objects can be equipped with method level security checks, object pools, and JIT events provided by COM services. In addition, the utility included with .NET allows you to create new .NET business objects interact with the legacy COM components.

To create an enterprise application with a C #, you can create a class library item including a data access object and another. In development, you can use console projects to test your class. Extreme programming enthusiasts can establish a console project to automate testing from a batch of files to the entire unit, while it will not be interrupted.

Note that C # and .NET may affect your reusable class's physical packaging. In the past, many developers put many classes into a single physical component, because this can make the deployment easier; and if there is a version problem, you know where to check. Because configuration .NET business formation only needs to be easily copied to the directory. Developers can now encapsulate their own classes in more logical, discrete components, without "DLL Hell" issues.

Finally, but equally, the C #-based ASP.NET page provides an excellent medium for the establishment user interface. Because the ASP.NET page is compiled, they will make it very fast. Because they can be tried in Visual Studio .NET IDE, they are robust. Because they support a comprehensive language feature, such as early binding, inheritance, and modular, code based on C #-based ASP.NET pages is neat, easy to maintain.

Experienced developers have skeptical attitudes to new technologies or languages ​​for big advertising, and it is difficult to use a new platform because it is recommended. If you are a business developer in the IT department, or you only provide application services through World Wide Web, C # and .Net provide at least four reliable benefits, which does not include some strange features, such as XML Web Services and server-side controls:

❑❑ Component conflicts will become rare, deployment will also become simpler, because different versions of the same component can run in parallel in parallel in the same machine without conflicting.

❑ Your ASP.NET code is no longer obscured.

❑ You can regulate a lot of functionality in the .NET underlying class library.

❑ For applications that require a Windows Forms user interface, it is easy to write such programs with C #.

Due to the emergence of Web Forms and Internet-based applications, Windows Forms have been neglected in recent years. However, if you have lack experience in JavaScript, ASP, or other related technologies, Windows Forms is still a feasible and convenient to create user interface selection. Remember to distinguish your code hierarchical so that user interface can be separated from business logic and data access code. The purpose of this can make you migrate your application to the you in the future. Of course, Windows Forms will continue to rule dominance in user interface technology in the family and small-scale business applications. 1.8 small knot

In this chapter we introduced a lot of basic knowledge, let us briefly review the important aspects of .NET Framework knowledge and his relationship with C #. We first discussed why all .NET-oriented languages ​​were first compiled into a Microsoft Intermediate Language (IL), because only this can be compiled into the local code and executed by Common Language Runtime (CLR). We also discussed these .NET's features played in compilation and implementation:

❑ 程序 assembly and .NET basic class

❑ COM components

❑ JIT compilation

❑ Application domain

❑ Garbage collector

Figure 1-4 shows how these features play a role in compilation and execution:

Figure 1-4

We also discussed the characteristics of IL, especially strong data types and object-oriented properties. We discussed how these features affect the .NET-oriented language, including C #. We also discussed the strong type characteristics how to give the IL language interoperability, and the CLR, such as garbage recovery, and safety.

Finally, we discuss how to create .NET technology-based applications including ASP.NET with C #.

We will introduce how to write C # code in the next chapter.

转载请注明原文地址:https://www.9cbs.com/read-62447.html

New Post(0)