Programming----Microsoft on a new platform. NET Platform series article (translation/Zhao Ning)

Source: Internet
Author: User
Tags constructor garbage collection numeric object object reference win32
Programming | Microsoft programming on a new platform
----Microsoft. NET Platform series of articles
Translation/Zhao Ning
For more than a year, I've been focusing on Microsoft's. NET CLR (Common language Runtime: Common Language Runtime) platform. In my opinion, most new developments will be geared toward this platform in the future because it makes application development easier and simpler. At the same time, I expect the current application development to move quickly. NET platform.
To help developers master this new platform, this article and future series of articles will be specifically targeted. NET discusses various programming issues. I will assume that you are already familiar with object-oriented programming concepts. The content of each article is focused on the specific common language runtime programming topics that are not selected. All. NET developers must know these topics.
When displaying code examples, I must choose one of several languages that support the. NET CLR. I decided to use C #. It is a new language designed by Microsoft.
My goal is to introduce different programming topics and provide you with some ideas on how to implement them. So I don't want to fully describe each topic and all the nuances that are relevant to it. Refer to the common language runtime or language documentation for a complete, detailed description of the topic.

Real Object Oriented design
For programmers who use the Win32 SDK, access to most operating system features is achieved through a set of independent functions that are output from the dynamic link library. These independent functions are very easy to invoke from a non object-oriented language such as C. But for a new developer, it is quite daunting to face thousands of independent functions that seemingly have nothing to do with them. More difficult is that many function names start with the word "get" (such as GetCurrentProcess and Getstockobject). In addition, the Win32 API has been in the calendar year and Microsoft has added new functions, and these new functions are still compared to functions. have similar semantics, but there are some differences in the features provided. You can often recognize newer functions because their names are similar to the original function names (like Createwindow/createwindowex,createtypelib/createtypelib2 and my favorite createpen/ Createpenindirect/extcreatepen
All of these problems make programmers feel that Windows development is difficult. With. NET platform, Microsoft has finally provided a fully object-oriented development platform for the frustrated developers. Platform services are now divided into separate namespaces (e.g., system.collections,system.data,system.io,systemsecurity,system.web, etc.) and each namespace contains a set of related classes that allow access to platform services.
Because class methods can be overloaded, methods with little behavioral differences have the same name, and can only be seen from the prototype. For example, a class might provide three different versions of the CreatePen method. All methods do the same thing: Create a pen. However, each method has a different set of parameters and behaves differently. In the future, Microsoft will also create a fourth CreatePen method and cooperate with the previous class methods.
Because all platform services are implemented through this object-oriented approach, software developers should have an understanding of object-oriented programming. Object-oriented methods also bring some other features, such as the use of inheritance and polymorphism to create a specialized version of the base class library type easily. Again, I strongly recommend mastering these concepts, which is for Microsoft. NET Framework is important.

System.Object
In. NET, each object is derived from System.Object. That is to say, the following two types of definitions (using C #) are the same:

Class Jeff {
...
}

And

Class Jeff:System.Object {
...
}

Because all objects are derived from System.Object, you can guarantee that each object has a minimal set of features. Table one is the public method in System.Object.
The common language runtime requires all objects to be created with the new operator (invoke the newobj il Directive). The following code demonstrates how to create an object instance of the Jeff Type, which was declared earlier:
Jeff J = new Jeff ("ConstructorParam1");

The new operator creates an object by allocating the number of bytes from the heap, depending on the type you specify. It initializes the cost members of the object. Each object has some additional bytes that the common language runtime uses to manage objects, such as an object's Xu Quai pointer and a reference to a synchronization fast.
When the constructor of a class is invoked, the passed arguments are specified in the new statement (the example is a string "ConstructorParam1"). Note Most languages compile constructors so that they call the base class constructor, but this is not necessary in the common language runtime.
When new implements all of the actions I mentioned, it returns a reference to the newly created object. In the example code, the reference is stored in the variable J, and its type is Jeff.
In addition, the new operator does not have a pairing operation (delete). That is, there is no way to explicitly release or destroy an object. The common language runtime provides a garbage collection environment that is automatically probed and automatically releases and destroys objects when the object is no longer in use or is no longer accessed, as this topic will be presented in the next discussion.

Casts of data types
In the programming process, it is very common for an object to be cast from one data type to another. In this section, I'll discuss the mandatory data type conversion rules for the object. To do this, first look at the following code:

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

The previous code was compiled and executed correctly because of an implied coercion type conversion. The new operator returns a reference type for Jeff, but O is a System.Object reference type. Because all types (including the Jeff type) can be cast to System.Object, the implied coercion type conversion is successful. However, if you execute the following code, there will be a compiler error because the compiler does not provide a cast of the base type to the derived type.

Jeff j = o;

In order to be able to compile, you must insert the following explicit coercion type conversion:
Jeff J = (Jeff) o;
It is now possible to compile and execute successfully.
Let's look at another example:

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

The first line creates a System.Object type object. The second line of code attempts to convert the System.Object reference type to the Jeff reference type. Both lines of code can be compiled through. But at execution time, the second line of code produces a InvalidCastException exception that, if not captured, forces the application to terminate.

When the second line of code executes, the common language runtime verifies that the object that O refers to is the Jeff type object (or any Jeff-derived type). If so, the common language runtime allows type conversions to be enforced. Otherwise, if O refers to an object that has nothing to do with Jeff Type, or a base class for Jeff, the common language runtime prevents this unsafe coercion of type conversions and produces InvalidCastException exceptions.

C # uses the AS operator to provide an alternative way to enforce type conversions:

Jeff J = new Jeff (); Create a new Jeff Object
System.Object o = j as System.Object; Cast J to a System.Object object
Now o means Jeff Object

The as operator attempts to cast an object to the specified type. Unlike a normal cast, however, if the object's type casts unsuccessfully, the result is that the null,as operator will never throw an exception. A NullReferenceException exception is generated when a reference to a faulty forced type conversion occurs. The following code demonstrates this situation.

System.Object o = new System.Object (); To create a new object
Jeff J = o as Jeff; Cast O to a Jeff object
The above cast fails: No exception is thrown, and J is set to null

J.tostring (); A NullReferenceException exception occurred while accessing J

In addition to the as operator, C # also provides an IS operator. It checks if an object instance is compatible with a given type and determines whether the result 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 that if the object reference is the Null,is operator always returns false because the object cannot be checked for its type.
To be sure you understand what you just said, assume that the following two types of definitions exist.

Class B {
int x;
}

Class D:b {
int x;
}

Now, see figure II to see which line of code is compiled and executed successfully (ES), which line of code causes a compiler error (CE), and which line of code causes the common language runtime error (RE).

The collection and the name space
A set of types can be divided into collections (one or more file sets) and expanded. There can be only a single namespace in a collection. For application developers, namespaces are like logical groupings of associated types. For example, the base Class library collection contains many namespace names. The System namespace includes core low-level types such as Object base type, Byte, Int32, Exception, Math, and delegate, and System.Collections namespaces include types such as Aarrylist, Bitaarry, queue, and stack.

For the compiler, the namespace is simply a type name with a long name, and its uniqueness is guaranteed by separating some symbol names with a period. For compilers, the object type in the System namespace is only represented by a type called System.Object. Similarly, the queue type in the System.Collections namespace is simply represented by the identifier System.Collections.Queue.
The runtime engine does not know any information about the namespace. When you access a type, the common language runtime only needs to know the full type name and which collection contains this type of definition so that the common language runtime can load the collection correctly, finding the type to access and handling it.
Programmers often want to express algorithms in the most concise way, but it is extremely troublesome to refer to each class type with a fully qualified name. Therefore, many programming languages provide a statement that instructs the compiler to add various prefixes to the type name until a match is implemented. When programming in C #, I often use the following statement at the front of the source code:

Using System;

When I refer to a type in code, the compiler needs to make sure that the type is defined and that my code accesses the type in the right way. If the compiler cannot find the specified type, it attempts to "System." Add to the type name and check that the resulting type name matches the existing type name. The preceding line of code allows me to use Object in my Code, and the compiler will automatically expand the name to System.Object. I'm sure you can easily imagine how much keyboard input has been omitted.
When checking for a type definition, the compiler must know which set contains the type so that the information and type information of the collection can be sent to the result file. To get the collection information, you must pass the collection that defines any reference type to the compiler.
As you can imagine, there are some potential problems with this design. For programming purposes, you should avoid creating names that conflict with the type. But in some cases, it's completely impossible. NET encourages component reuse. Your application can take advantage of components created by Microsoft, and you can also create another component with Richter. The components of these companies may all provide a type called foobar, and-microsoft's foobar does something completely different from what Richter Foobar does. In this case, you cannot control the naming of class types. To refer to Microsoft's FooBar, you use Microsoft.foobar, in order to refer to Richter's FooBar, you use Richter.foobar.
In the following code, the reference to the foobar is ambiguous. The compiler reports an error, but in fact the C # compiler picks a possible case for the Foobar type, and you don't find the problem until run time:

Using Microsoft;
Using Richter;

Class MyApp {
method void Hi () {
FooBar f = new FooBar (); Ambiguous, compiler picks
}
}

To eliminate this ambiguous reference, you must explicitly tell the compiler which foobar you want to create.

Using Microsoft;
Using Richter;

Class MyApp {
method void Hi () {
Richter.foobar f = new Richter.foobar (); Explicit references
}
}

Another form of statement is to allow you to create aliases for individual types, which is convenient if you only use several types of namespaces and do not want to pollute the entire namespace with all namespace types. The following code demonstrates another way to resolve a type-ambiguous problem.

Define Richterfoobar as Richter.foobar alias
Using Richterfoobar = Richter.foobar;

Class MyApp {
method void Hi () {
Richterfoobar f = new Richterfoobar (); No mistakes
}
}

This method is useful for eliminating type ambiguity, but it still exists in unsatisfactory places. Suppose that Australia's darts (boomerang) Company (ABC) and Alaska's Ship (boat) company (also known as ABC) have created a single type for two companies. Perhaps two companies have created namespaces called ABC, which contain a type called Buyproduct in the namespace. Anyone trying to develop the need to buy darts and ship apps will get into trouble unless the programming language provides a way to differentiate between two companies-not just the namespaces of two companies.
Unfortunately, the C # language only supports namespaces and does not provide any way to describe the collection in any detail. But in fact there are not many times when this problem is encountered, it is a rare problem. If you are designing a component type that you want a third party to use. It is recommended that you define a type in a namespace so that the compiler can easily exclude type problems. In fact, you should use the company's full name (not just the first letter) as the top-level namespace name to reduce the likelihood of conflict. You can see Microsoft using "Microsoft" as the name space.
It's easy to write a namespace declaration in your code to create a namespace. Just like the following:

namespace CompanyName {//CompanyName
Class A {//Companyname.a
Class B {...}//COMPANYNAME.A.B
}

namespace X {//companyname.x
Class C {...}//COMPANYNAME.X.C
}
}

Note that the namespace is a public type that is implied. This cannot be changed by any access modifiers. But you can define the type in the internal namespace (which cannot be used outside the collection) or define the type in the public namespace (which can be accessed by any collection). namespaces represent only logical restriction policies, and accessibility and packaging are done by putting namespaces into a collection.
In the next discussion, I will elaborate on all. NET programmers must master for simple data types, reference types, and numeric types. For each one. NET programmer, it is important to have a thorough understanding of numeric types.


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.