. NET new platform programming

Source: Internet
Author: User
Tags definition constructor functions garbage collection inheritance variable versions win32
For the "past year" or so, I ' ve been focusing my attention on the Microsoft. NET common Language Runtime. In my opinion, most new development'll target this platform because it makes application development so much easier and Faster. I also expect existing application development. NET at a toward rapid.

For the past year, I have been paying attention to Microsoft. NET common language runtime platform. In my opinion, most of the new development will go to this platform, because he will make development very simple and fast. I also hope that the existing development will be transferred to. NET as soon as possible.

To help developers embrace the this new platform, the My next few columns'll focus on various programming issues the specific to. NET. I ' ll assume that you are already familiar with object-oriented programming concepts. Each column would focus on run-of-the-mill programming topics that are specific to the common language. All. NET developers must become aware of these topics.

To help developers understand the new platform, my next columns will focus on a variety of issues. NET programming problems. I assume you are already familiar with object-oriented programming concepts. Each column will focus on programming issues for the general language runtime. All developers must be aware of these issues.

When showing code examples, I had to choose one of the many languages the. NET Support Common language. The most neutral language to choose would have been intermediate (IL) language. However, it is unlikely that IL assembly would be the most popular language, so I ' ve decided to use C #. C # is the new language that Microsoft designed specifically for the development of managed code. While the sample code shown is C # and the explanations are geared toward coding with C #, the concepts discussed are Exposed by the common language runtime and therefore apply to any language that targets it.

In giving a programming example, I need to start with the. NET common language runtime supports the programming language to select one. The most should choose is the Intermediate assembly language. However, unfortunately it is not the most popular language, so I choose C #. C # is a new language that Microsoft has designed specifically to develop controlled code. Although the example is in C # and the explanation is for C #, the concept of discussion is appropriate for all programming languages that use the common language runtime.

My goal are to introduce various programming topics and to give you some idea of how they ' re implemented. It isn't my goal to fully describe each topic and all nuances it. For complete details on any topic presented, please refer to the common language or runtime language. Now, with the introduction out of the way, let ' s begin ....

My goal is to introduce a variety of programming issues and give you some knowledge of how they are implemented.


True object-oriented Design

Real Object Oriented design

For programmers using the Win32? SDK, access to most of the operating system features was through a set of standalone functions exported from DLLs. These standalone functions are are very easy to call from non-object-oriented languages like C. However, it is quite daunting for new developers to face literally thousands of independent functions , seem unrelated. Making things more difficult is the fact this many functions start with the word get (for example, GetCurrentProcess and G Etstockobject). In addition, the Win32 API has evolved over the years and Microsoft has added new functions has similar semantics-but O Ffering slightly different features over the earlier functions. You can usually identify the newer functions because their names function ' s name (are as similar Tewindow/createwindowex, Createtypelib/createtypelib2, and one of my personal favorites:createpen/createpenindirect/ Extcreatepen).

For programmers using the Windows Master SDK, most operating system features are accessed through a series of independent functions derived from DLLs. These orphaned functions can be easily invoked in a non-object-oriented language such as C. However, the headaches for new developers are to face many unrelated functions that appear to be independent on the surface. But in fact many functions have complex relationships, such as many functions that begin with Word get (for example: GetCurrentProcess and Getstockobject). In addition, WIN32API developed for many years, Microsoft added a number of new functions, it looks like the name is very similar to the use of the earlier functions are slightly different. You may often think of a new function as the old one just because the name is very similar (for example: Createwindow/createwindowex, CREATETYPELIB/CREATETYPELIB2, CreatePen/ Createpenindirect/extcreatepen).

All of this issues have given programmers the impression that developing for Windows? is difficult. With. NET, Microsoft are finally addressing developers ' cries for help by creating a entirely object-oriented. Platform services are now divided into individual namespaces (such as System.Collections, System.Data, System.IO, SYSTEM.S Ecurity, system.web, and, and each namespace contains a set of related class types that allow access to the Platfor M ' s services.

All of these questions are hard to impress people who are engaged in Windows development. With. NET, Microsoft created a complete object-oriented platform that finally solved the problem that plagued developers. Platform services are now divided into opposing namespace (the word is difficult to translate correctly or in English) (e.g. systems, collections, system data, System IO, system security, System Web, etc.), and each namespace contains a series of related classes for accessing platform services.

Since class methods May is overloaded, methods that differ just slightly in their behavior are given identical names and D Iffer only by their prototypes. For example, a class might an offer three different versions of a CreatePen method. All methods do the same thing:create a pen. However, each method takes a different set of parameters and has slightly different. In the future, should Microsoft need to create a fourth CreatePen method, the new method would fit seamlessly into the CLA SS as a first-class citizen.

Because class methods can be overloaded, the parameters of a method with the same name may have different effects. For example, a class has three different versions of the CreatePen method. All the way to do the same thing, create a pen. However, each method has different parameters and subtle differences in behavior. In the future, Microsoft may want to create a fourth CreatePen method, and the new method will become a member of this class.

Since all platform services are offered via this object-oriented paradigm and software developers should have some understand ing of object-oriented programming. The object-oriented paradigm enables other features as. For example, it are now easy to create specialized versions of the base class library ' s types using inheritance and Polymor Phism. Again, I strongly suggest you become familiar with this concepts, as they are now critical to working with the Microsoft The. NET Framework.

Because all platform services are provided through object-oriented methods, software developers should have some knowledge of object-oriented. Object-oriented has many advantages. For example, it is easy to use inheritance and polymorphism to create a special version of the underlying class library. Again, I strongly recommend familiarity with these concepts because of these and Microsoft's. NET architecture is closely related.


System.Object

System objects

In. NET, every object are ultimately derived from the System.Object type. This means the following two type definitions (shown using C #) are identical:

In. NET, each object is derived from System.Object. means that the following two types of definitions are the same.

Class Jeff {


???

}


and

And


Class Jeff:System.Object {


???


}


Since all object types are ultimately derived to System.Object, you are guaranteed that every object of every type has a Minimum set of capabilities. The public methods available in the System.Object class, are shown in Figure 1.

Because all object types derive from System.Object, this ensures that each type of object has a set of most basic functions. System.Object public method as shown in Figure 1

The common language runtime requires that all object instances is created using the new operator (which calls the newobj I L instruction). The following code shows how to create a instance of the Jeff type (declared previously):

The common language runtime requires that all objects be created with a new operator (invoke the newobj il Directive). The following code shows how to create an instance of the Jeff type.


Jeff J = new Jeff ("ConstructorParam1");


The new operator creates the "object by allocating" number of bytes required for the specified type from the managed P. It initializes the "object" overhead members. Every object has some additional bytes this common language runtime uses to manage the object, such as the object ' s VI Rtual table pointer and a reference to a sync block.

The new operator allocates the memory required by the specified type from the controlled heap to create the object. It initializes the member of the object. Each object has some additional bytes that are used by the common language runtime to manage objects, such as virtual table pointers for objects and synchronous lock references.

The class type ' s constructor is called, passing it any parameters (the string "ConstructorParam1" in the earlier example) specified in the call to new. Note that most languages would compile constructors so, they call the base type ' s constructor; However, this isn't required by the common language runtime.

When you create a new instance, the constructor for the class is invoked and some arguments are given to it. Note that most language-compiled constructors call the constructor of the base class, however, this is not required by the common language runtime.

After new has performed the operations I just mentioned, it returns a reference to the newly object. In the example code, this reference was saved in the variable J., which is of type Jeff.

By the way, the new operator has no counterpart. "Is", there is no way to explicitly free or destroy an object. The common language runtime offers a garbage-collected environment that automatically detects when objects are no longer b Eing used or accessed and frees the objects automatically, which is a topic I plan to cover in a upcoming of MSDN? Magazine.

After new completes all of the things I said, it returns a reference to a newly created object. In the example, the reference is saved to the variable J, and the type of J is Jeff. By the way, the new operator does not have a corresponding operator, which means there is no clear way to release or unregister an object. The common language runtime provides a garbage collection environment that detects automatically if an object is no longer used or accessed and is automatically deleted. This is the topic that I will discuss in the next MSDN Magazine.

Casting Between Data Types

converting data types

When programming, it's quite common to cast an object from one data type to another. In this section, I'll look at the rules so govern how objects are cast between data types. To start, look in the following line:

The type of object is often programmed to be converted, and in this part we look at the rules of object type. Take a look at the following line of procedures:


System.Object o = new Jeff ("ConstructorParam1");


The previous line of code compiles and executes correctly because-is-an there cast. The new operator returns a reference to a Jeff type, but O's a reference to a System.Object type. Since all types (including the Jeff type) can being cast to System.Object, the implied cast is successful.

However, if you execute the "following line", you have a compiler error since the compiler does not provide a implicit cast From a base type to a derived type.

This line of programs can be compiled correctly because this is an implicit type conversion. The new operator returns a reference to the Jeff type, but O is a System.Object type. Because all types are derived from System.Object, they can be converted to System.Object types. However, if you execute the following line, you will generate a compilation error and cannot do an implicit conversion from the base class to the derived class.


Jeff j = o;


To get the command to compile, you must insert a explicit cast, as follows:

To compile through, you must add a cast.


Jeff J = (Jeff) o;


Now the code compiles and executes successfully.

Let ' s look at another example:

Now the code can be compiled and run, and then look at another example


System.Object o = new System.Object ();

Jeff J = (Jeff) o;


On the ' the ', I have created an object of type System.Object. On the second line, I am attempting to convert a reference of type System.Object to a reference of type Jeff. Both lines of the code compile just fine. However, when executed, the second line generates a InvalidCastException exception, which if not caught, forces the appli cation to terminate.

When the second line of code executes, the common language runtime verifies, the object referred to by O in fact a Object of type Jeff (or any type derived from type Jeff). If so, the common language runtime allows the cast. However, if the object referenced by O has no relationship to Jeff, or is a base class of Jeff, then the common language R Untime prevents the unsafe cast and raises the InvalidCastException exception.

In the first line, I create an object, the type is System.Object, and in the second line, I try to convert the System.Object type reference to the Jeff type. Both lines of code can be compiled correctly. However, at run time, the second line of code produces a InvalidCastException, and if this exception is not caught, then the program terminates.

When the second line of code runs, the common language runtime verifies that the type of object o reference is a Jeff type, and if so, the common language runtime allows transformations. If the O-referenced object is not related to Jeff or Jeff's base class, then the common language runtime will prohibit this unsafe conversion and produce an exception.

C # offers another way to perform a cast using the as operator:


Jeff J = new Jeff (); Create a new Jeff object creates a fresh Jeff objects

System.Object o = j as System.Object; Convert to Object

O now refers to the Jeff Object o reference one of Jeff objects


The as operator attempts to cast a object to the specified type. However, unlike normal casting, the as operator'll never throw an exception. Instead, if the object ' s type cannot be cast successfully, then the "result is null." When the Ill-cast reference is used, a NullReferenceException exception would be thrown. The following code demonstrates this concept.

The as operator is used to attempt to convert an object to a specified type. However, unlike normal conversions, the as operator does not throw an exception. Also, returns null if the object's type cannot be converted successfully. When an incorrect reference is used, this exception is thrown NullReferenceException. The following code illustrates this concept.


System.Object o = new System.Object (); Creates a new object

Jeff J = o as Jeff; Casts O to a Jeff

The cast above Fails:no exception is raised but J was set to null


J.tostring (); Accessing J generates a NullReferenceException


In addition to the as operator, C # also offers is operator. The IS operator checks whether an object instance are compatible with a given type and the result of the evaluation is eith Er True or False. The IS operator would never raise an exception.

In order to match the as operator, C # also provides an IS operator. The IS operator checks whether an object is of a type, and the return value is true or false. The IS operator does not produce an exception.


System.Object o = new System.Object ();

System.Boolean B1 = (O is System.Object); B1 is True

System.Boolean B2 = (O is Jeff); B2 is False


Note, if the object reference is null, the IS operator always returns FALSE since there are no object available to check it S type.

To make sure your understand everything just presented assume that following two class definitions.

Note that if the object reference is a Null,is operator returns false because there is no object to check the type.


Class B {

int x;

}


Class D:b {

int x;

}


Now, check Figure 2 to which lines would compile and execute successfully (ES), which would, cause a compiler error (CE ), and which would cause a common language error (RE).

See figure 2, which line will compile correctly, which will produce a compilation error, and which row will produce a run-time error.


Assemblies and namespaces

A collection of types can be grouped together to an assembly (a set of one or more files) and deployed. Within an assembly, individual namespaces can exist. To the application developer, namespaces look like logical groupings related of types. For example, the base Class library assembly contains many namespaces. The System namespace includes core low-level types such as the Object base type, Byte, Int32, Exception, Math, and Delegat E, while the System.Collections namespace includes such types as ArrayList, BitArray, Queue, and Stack.

Collections and namespaces

Types of the same class can be grouped together to form a set. In the collection, there is an independent namespace allowed. For developers, namespace is like a logical group of related classes. For example, the base Class library collection includes many namespace. The low-level types of the System namespace core are the object base class, Byte,int32,exception, Math, and Delegate, and System.Collections Namespace includes these types of ArrayList, BitArray, Queue, and Stack.


To the compiler, a namespace are simply a easy way of making a type ' s name longer and ensuring uniqueness by preceding the Name with some symbols separated by dots. To the compiler, the Object type in the System namespace really just identifies a type called System.Object. Similarly, the Queue type in the System.Collections namespace simply identifies a type called System.Collections.Queue.

For compilers, namespace is the only simple way to guarantee the name of a type, with different names and symbols separated by dots. An Object class can be written as System.Object in System namespace. Similarly, the Queue class can be written as System.Collections.Queue in System.Collections namespace.

The runtime engine doesn ' t know anything about namespaces. When you are in Access a type, the common language runtime just needs to know the full name of the type and which assembly NS the definition of the type so this common language runtime can load the correct assembly, find the type, and Manipu Late it.

The runtime engine does not know that there are namespace, and when you access a type, the common language runtime only needs to know the full name of the type and in which set it has this type of definition so that the common language runtime can load lookups and operations correctly.

Programmers usually want the most concise way of expressing their; It is extremely inconvenient to refer to every class type using its fully qualified name. For this reason, many programming languages offer a statement which instructs the compiler to try appending various s to a type name until a the match is made. When coding in C #, I usually place the following line at the top's My source code modules:

Programmers often want to express expressions in the simplest way, so it's more difficult to refer to a class in full name. Therefore, many program languages provide a directive that allows the compiler to add prefixes. When I use C #, I usually add the following statement at the beginning of the program.


Using System;


When I refer to a type in my code, the compiler needs to ensure this type is defined and this my code accesses the Typ E in the correct way. If the compiler can ' t find a type with the specified name, it tries appending "System." to the type name and checks if the Generated name matches an existing type. The previous line of code allows me to use Object in my Code, and the compiler would automatically expand the name to Syste M.object. I ' m sure you can easily imagine so much typing this saves.

When I refer to a type in my code, the compiler needs to get the definition of this type and make sure my code accesses it correctly. If the compiler cannot find the definition of the type by name, it tries to add the "system" prefix to find it. The preceding line of code allows me to access the Object class, which automatically turns the name into System.Object. It is conceivable that this will be a lot less dozen words.

When checking for a type ' s definition, the compiler must know which assembly contains the "type so" assembly ation and the type information can is emitted into the resulting file. To get the assembly information, your must pass the assembly this defines any referenced types to the compiler.

When examining a type definition, the compiler needs to know which collection contains the type definition information so that it can be added to the result file. To get the collection information, you give the compiler the set that contains the reference type definition.


As you might imagine, there are some potential and this scheme. For programming convenience, your should avoid creating types that have conflicting. However, in some cases, it is simply not possible. . NET encourages the reuse of components. Your application may take advantage of a component created by Microsoft and another component by me. Both of companies ' components may offer a type called FooBar

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.