A comparative Overview of C # Chinese version (iv)

Source: Internet
Author: User
Tags arrays case statement execution garbage collection goto naming convention visual studio support microsoft
When considering what C + + is doing, Java is doing a good deed, simplifying the issue of how parameters are passed. In C + +, there is no method in C + +, which should be called "function" or "member function", and the parameters and method calls are made unnecessarily complicated by passing values, references, pointers, such as int, int*, and int&. C # explicitly passes a reference, whether it is a method declaration or a call. It greatly reduced the confusion. Because of the syntax of C + +, sometimes you do not know whether you are using an object or an object reference, there is a sample after this, and the same goal as Java, but C # is more expressive. Clearly this is the gist of C #-it does not circle programmers in a circle so they have to go around a big bend to get something done. Do you remember Java? In the Java Guide, we recommend how to solve the problem of passing references, you should pass an array of 1 elements to save your values, or another class to hold the value.
Nasa
#include "stdafx.h"
Class Parentcls
{
Public
virtual void F () {printf ("parentcls\t");}
};
Class Childcls:public Parentcls
{
Public
virtual void F () {printf ("childcls\t");}
};
void Test1 (Parentcls pc) {pc.f ();}
void Test2 (parentcls& pc) {pc.f ();}
int main (int argc, char* argv[])
{
Childcls cc;
Test1 (cc);//Output PARENTCLS
Test2 (cc);//Output CHILDCLS
Only look at the use of the use, is not aware of the reference you are using or objects, but the results are very different!
return 0;
}

15. Characteristics
Both C # and Java's compiled code includes information similar to the field access level. C # expands the ability to compile custom information about any element in a class, such as classes, methods, fields, or even independent parameters, and to get that information at run time. Here's an example of a very simple class that uses attributes:
[AuthorAttribute ("Ben Albahari")]
Class A
{
[Localizable (true)]
public string text//"should be public string text or public System.String text if there is no previous using System"
{
get {return text;}
//...
}
}
Java uses a pair of/** */and @ Tag annotations to include additional information about classes and methods, but this information (except @deprecated "Java1.1 version and later") is not build into bytecode. C # uses predefined attributes to obsolete attributes, the compiler can warn you, eliminate waste code (like @deprecated), and use the conditional feature to make conditional compilation. Microsoft's new XML Library uses attributes to express how fields are serialized into XML, which means you can easily serialize a class into XML and rebuild it again. Another appropriate application of the feature is to create a truly powerful class browsing tool. The C # Language specification explains in detail how to create and use attributes.
16.switch Statement
Switch statements in C # can use integers, characters, enumerations, or (unlike C + + or Java) strings. In Java and C + +, if you omit a break statement in any of the case statements, you are at risk of other execution of the case statement. I can't figure out why this little-needed and error-prone behavior is the default behavior in both Java and C + +, and I'm happy to see that C # doesn't look like this.
Because C # does not support running from one case label to another. If necessary, you can use goto case or goto default implementation.
17. Predefined Types
C # Basic types are basically the same as Java, except that the former also adds unsigned types. C # has sbyte, Byte, short, ushort, int, uint, long, ulong, char, float, and double. The only surprising thing about this is that there is a 16-byte "12-byte" floating-point value type decimal, which makes full use of the latest processor.
To add, although the decimal occupies 128 digits, but its range of values than float (32-bit), Double (64-bit) far smaller, but its precision is much higher than the latter two, can meet the high accuracy of financial calculation, etc.
18. Field Modifiers
field modifiers in C # are basically the same as Java. In order to represent fields that cannot be modified, C # uses the const and readonly modifiers. The const field modifier is like the final field modifier in Java, where the actual value of the field is compiled into part of the IL code. A read-only field evaluates values at run time. For a standard C # library, this can be upgraded without destroying your deployed code.
19. Jump Statements
There is no more surprising place, except perhaps the infamous goto statement. However, this is very different from the goto statement of BASIC, which we remember to bring trouble 20 years ago. A goto statement must point to a label, "the Goto statement must be within the scope of the label, or in other words, allow only the goto statement to pass control over a nested scope, and not pass control into a nested domain or a select branch in a switch statement. The so-called goto case statement ". The use of pointing labels is similar to continue. Java in the label, the degree of freedom of a few "in Java, break and continue statements can be followed by the label." In C #, a goto statement can point to any place in its scope that refers to the same method or finally program block "If the goto statement appears within a finally statement block, the destination of the Goto statement must also be within the same finally statement block". Continue statements in C # are basically equivalent in Java, but C # cannot point to a label.
"Java takes goto as a reserved word, but does not implement it"
20. Composition, namespace and access level
In C #, you can organize components (classes, structs, delegates, enumerations, and so on) in your source code into files, namespaces, and compositions.
The name space is just the grammatical honeyed words of the long class name. For example, you don't have to write Genamics.WinForms.Grid so you can declare the class Grid and wrap it up:
Namespace Genamics.winforms
{
public class Grid
{
//....
}
}
For classes that use Grid, you can use the Using keyword to import "genamics.winforms: Using a" instead of using its full class name Genamics.WinForms.Grid.
A combination is an EXE or DLL compiled from a project file. NET runtime uses configurable features and versioning rules to create them into the mix, which greatly simplifies deployment-no need to write the registry, just copy the combination to the relevant directory. A composition can also form a type boundary to resolve a class name conflict problem. Multiple versions of the same combination can coexist in the same process. Each file can contain multiple classes, multiple namespaces. A name space can span several combinations. In this way, the system will be able to achieve greater freedom.
There are five levels of access in C #: Private, internal, protected, internal protected and public: internal protected of course, protected internal, There is no other combination ". Private and public and Java mean the same. In C #, the access level is not indicated by private, not by package scope. Internal access is limited to the composition rather than the namespace (which is more similar to Java). Internal protected is equivalent to Java protected. Protected is equivalent to the Java private protected, which has been deprecated by Java.
21. Pointer Operation
In C #, pointer operations can be used in methods that are marked as unsafe modifiers. When the pointer points to an object that can be garbage collected, the compiler forces the fixed keyword to use to fix the object. This is because the garbage collector relies on moving objects to reclaim memory. But if the object that it refers to is moved when you use the original pointer, your pointer will point to the garbage. I think it's a good choice to use the unsafe keyword here-it doesn't encourage developers to use pointers unless they really want to.
22. Multidimensional Arrays
C # can create jagged arrays an array of arrays is an array of elements. The dimensions and sizes of jagged array elements can be different and multidimensional arrays. A jagged array is very similar to a Java array. Multidimensional arrays make it possible to express specific problems more efficiently and more accurately. Here is an example of this array:
int [,,] array = new int [3, 4, 5]; Create an array
int [1,1,1] = 5;//: This line of code is wrong: should be array[1,1,1] = 5;
Using jagged arrays:
int [][][] array = new int [3][4][5]; "The line code is wrong, should be: int [][][] array = new int[3][][];"
int [1][1][1] = 5; "The line code is wrong: should be array[1][1][1] = 5;" "Be careful with jagged arrays"
If combined with the structure, C # provides high efficiency, making arrays a good choice in the field of graphics and mathematics.
23. Builder and destructor
You can specify optional constructor parameters:
Class Test
{
Public Test (): This (0, null) {}
public Test (int x, object o) {}
}
You can also specify a static constructor:
Class Test
{
Static int[] Ascendingarray = new int [100];
Static Test ()
{
for (int i = 0; i < ascendingarray.length; i++)
Ascendingarray [i] = i;
}
}
The naming of the destructor takes the C + + naming convention, using the ~ symbol. The destructor can only be applied to reference types, value types are not available, and cannot be overloaded. The destructor cannot be invoked explicitly because the lifetime of the object is controlled by the garbage collector. Each destructor in an object's inheritance hierarchy is invoked before the memory occupied by the object is reclaimed.
Although similar to the naming of C + +, destructors in C # are more like Finalize methods in Java. This is because they are invoked by the garbage collector instead of being explicitly invoked by the programmer. And, like the Java finalize, they are not guaranteed to be invoked in all cases (which often makes everyone who finds it first to be shocked). If you are accustomed to using deterministic destructors (you know when the destructor of an object is invoked), you must adapt to this different programming model when you move to Java or C #. Microsoft recommended and implemented, throughout the whole. NET Framework is the Dipose mode. You define a Dispose () method for classes that need to be managed outside resources, such as graphics handles or database connections. For distributed programming,. NET Framework provides a basic model of conventions to improve the reference count problem for DCOM.
. Controlled execution Environment
    Comparisons between [C#/il code/clr] and [java/bytecode/JVM] are inevitable and justifiable. I think the best way is to first figure out why these technologies are created.
C and C + + to write programs, is generally the source code compiled into assembly language code, it can only run on a specific processor and a specific operating system. The compiler needs to know the target processor because different processor instruction sets are different. The compiler also needs to know about the target operating system, because different operating systems differ in the concepts of how to perform work and how to implement such basic C + + elements as memory allocations. This model has been hugely successful (most of the software you use may have been compiled this way), but it has its limitations:
L programs have no rich interfaces to interact with other programs (Microsoft COM is created to overcome this limitation)
L programs cannot be distributed in a cross-platform fashion
L cannot restrict the application to a safe operation in a sandbox
To solve these problems, Java uses the Smalltalk approach, which is compiled into bytecode and runs in virtual machines. Bytecode maintains the basic structure of the program before being compiled. This makes it possible for Java programs and other programs to interact with each other. Bytecode is also machine-neutral, which means that the same class file can run on different platforms. Finally, the fact that the Java language does not have an explicit memory operation (via pointers) makes it ideal for writing "sandbox programs."
The original virtual machine uses an interpreter to convert the byte code instruction stream to machine code. But the process was so slow that it was never attractive to programmers who were interested in performance. Today, most JVMs use JIT compilers, which are basically compiled into machine code-before they reach the scope of the class framework and before the method body executes. Before it runs, it is possible to convert Java programs into assembly language to avoid the memory load of startup time and Just-in-time compilation. This process does not need to remove the program's dependency on the runtime, as compared to compiling a Visual C + + program. The Java runtime, which is hidden under the term Java Virtual machine, handles many critical aspects of the process execution, such as garbage collection and security management. The runtime is also considered to be a controlled execution environment.
Although the terminology is a bit vague, the. NET basic model uses the same method as described above, although it does not use the interpreter. NET's important improvements will come from the improvement of IL's own design. The only way Java can match is to modify the bytecode specification to achieve strict compatibility. I do not want to discuss the details of these improvements, which should be left to the very individual developers who understand the bytecode as well as the IL code. 99% of developers like me are not going to study IL code specifications, here are some IL design decisions that are intended to improve bytecode:
• Provides better type neutrality (helps implement templates);
• Provide better language neutrality;
L always compile into assembly language before execution, never explain;
L can add additional declarative information to classes, methods, and so on. See 15. Characteristics;
Currently, the CLR also provides multiple operating system support, and provides better interoperability support for JVMS in other areas. See 26. Interoperability
25. The Library
Language is of no use if it has no library. C # is known for not having a core library, but it takes advantage of. NET Framework libraries (some of them are created in C #). This article focuses on the special point of the C # language, not the. NET, that should be explained in other text. To put it simply,. NET library includes rich threads, collections, XML, ado+, asp+, GDI +, and WinForm libraries. Now these + have become more and more. Netj ". Some libraries are cross-platform and some are dependent on Windows, read the next discussion on platform support.
26. Interoperability
I think it is more appropriate to divide interoperability into three parts: DE, and for those pursuing language interoperability, platform interoperability, and standard interoperability. Java is longer than platform interoperability, C # is longer than language interoperability. In terms of standard interoperability, both have their own length.
(1) Language Interoperability
The ability to integrate with other languages can only be distinguished by the degree of integration and ease. Both the JVM and the CLR allow you to write code in multiple languages, as long as they are compiled into bytecode or IL code. However. NET platform has done a lot of work-not only to compile code written in other languages into IL code, but also to enable multiple languages to freely share and expand each other's libraries. For example, Eiffel or Visual Basic programmers can import C # classes, overload their virtual methods, and C # objects can also use Visual Basic methods (polymorphic). If you doubt it, VB. NET has been greatly upgraded, and it has modern object-oriented features (cost and VB6 compatibility).
Languages written for. NET are generally inserted into the Visual Studio.NET environment, and you can use the same RAD framework if needed. This overcomes the impression that the use of other languages is "second-class citizens".
C # provides the P/invoke "Platform invocation service, platform invoke services," which is much simpler than Java JNI and C code (no DLL required). This feature is much like J/direct, which is a feature of Microsoft Visual J + +.
(2) Platform Interoperability
Generally, this means interoperability of the operating system. But over the past few years, Internet browsers have become more and more platform-like.
C # code runs in a controlled execution environment. This is an important step in enabling C # to run on different operating systems. However, some. NET Library is windows-based, especially the WinForms library, which relies on a plethora of Windows APIs. There is a porting from the Windows API to the UNIX system project, but it has not yet started, and Microsoft has no explicit hint to do so.
However, Microsoft has not neglected platform interoperability. NET Library provides an extensible capability to write html/dhtml solutions. For clients that can be implemented with html/dhtml, c#/. NET is a good choice. Java is a good choice for cross-platform projects that require a more complex customer interface. A version of Kylix-delphi that allows the same code to be compiled both on Windows and Linux, and may also be a good choice for cross-platform solutions in the future.
(3) Standard Interoperability
Almost all standards, such as database systems, graphics libraries, Internet protocols, and object communication standards, such as COM and corba,c#, are accessible. As Microsoft has a right or a great role to play in setting these most standards, their support for these standards is in a good position. They certainly offer less standard support for commercial motives (I'm not saying they are fair)-for things that compete with them-such as CORBA (COM's competitors) and OpenGL (DirectX's competitors). Similarly, Sun's business motives (again, I'm not saying they are fair) mean that Java does not do everything in its ability to support Microsoft's standards.
Because C # objects are implemented as. NET object, so it is automatically exposed as a COM object. C # Therefore, you can expose both COM objects and COM objects. This allows you to integrate COM code and C # projects. NET is a framework that has the ability to eventually replace COM-but there are already so many deployed COM components that I believe are unequal. NET instead of COM, it has been replaced by the next wave of technology. But anyway, hope. NET can have a long and interesting history! J
27. Conclusion
So far, I hope to have given you a C # and Java, C + + in the conceptual comparison. In general, I believe that C # provides better expressiveness than Java and is better suited to writing code that has strict performance requirements, as well as Java elegance and simplicity, which is more appealing than C + +.

-Complete Full-

Related Article

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.