A Comparrative Overview of C # Chinese version
Author: Ben Albahari
Company: Genamics
Date: August 31, 2000, August 10, 2000.
Thanks to the following people support and feedback (in order to let): Don Box, C.R. Manning, Joe Nalewabau, John Osborn, Thomas Rhode & Daryl Richter.
Translator: glory
[Interportion: C # get started with the class! I hope that the translation of novices in the article will not affect the smoothness of reading. All program debugging environments in the translation are Microsoft Visual Studio.NET 7.0 Beta2 and Microsoft .NET Framework SDK Beta2. The code is the article, please read the code carefully J]
10. Operator overload
Using the operator overload mechanism, the programmer can create a class of simplicity (such as int, long, etc.). C # implements a limited version of the C operator overload, which allows such a brilliant example-complex operator overload performance.
In C #, operators == are non-virtual (operators that cannot be virtual), which is compared according to reference. When you build a class, you can define your own == operator. If you use your class in the collection, you should implement the IComparable interface. This interface has a Compareto (Object) method, if "this" is greater than, less than or equal to this object, it should return positive, negative, or 0 accordingly. If you want users to use your class with an elegant syntax, you can choose to define <, <=,> =,> methods. Numeric type (int, long, etc.) implements the IComparable interface.
Here is a simple example of how to handle and compare operations:
Public Class Score: IComparable
{
Int value;
Public score (int score)
{
Value = score;
}
Public static bool operator == (Score X, Score Y)
{
Return x.value == y.Value;
}
Public Static Bool Operator! = (Score X, Score Y)
{
Return X.Value! = y.value;
}
Public Int Compato (Object O)
{
Return Value - (Score) .value;
}
}
Score a = new score (5);
Score b = new score (5);
Object c = a;
Object d = B;
Compare A and B by reference
System.console.writeline (Object) a == (Object) b; / / The result is False
[Translation: The above sentence should be: system.console.writeline (object) a == (Object) b); / / result is false]
Compare the values of A and B:
System.console.writeline (a == b); / / The result is TRUE
Compared with C and D in reference
System.console.writeline (c == d); / / The result is False
Compare the values of C and D:
System.console.writeline ((iComparable) c) .compareto (d) == 0); / / The result is TRUE
You can also add <, <=,> =,> operators to the Score class. C # The compile period guarantees logically to appear an operator (! = And ==,> and <,> = and <=) must be defined together.
11. Polymorphism
Object-oriented language uses the false method to express polymorphism. This means that the derived class can have the same signature with the parent class, and the parent class can call the derived class method [Translation: This should be an object (or object reference, pointing to the pointer to the object)]. In Java, the method is default by default. In C #, you must use the Virtual keyword to be called by the parent class.
In C #, an OVERRIDE keyword is also required to indicate a method of using a method to overload (or implement an abstract method).
Class B // [Translation: Class B]
{
Public virtual void foo () {}
}
Class D: b // [Translation] should be Class D: B]
{
Public override void foo () {}
}
Trying to overload a non-virtual method will result in a compile time error unless the method is added to the "New" keyword to indicate that the method is intended to hide the parent class.
Class N: D // [Translation] should be Class N: D]
{
Public new void foo () {}
}
N n = new n ();
n.foo (); // Call N's Foo
((D) n) .foo (); // Call D's foo
((B) n) .foo (); // Call D's Foo
Compared to C , Java, the C # Override keyword makes it clear to see which methods are overloaded when reading the source code. However, it is advantageous to use the imaginary method. The first advantage is: avoiding the use of imaginary methods to improve the execution speed. The second point is to clearly know which methods will be overloaded. [Translation: From "not" here, these sentences are obviously not logical, but the original is this: "HOWEVER, REQUIRING The Use of the Virtual Method Has Its Pros and cons. The first pro is this Slightly Increased Execution Speed from Avoiding Virtual Methods. The Second Pro Is To make Clear What Methods Are Intended to Be Overridden. I think that if you will be changed to Keyword Method, it will be changed to Keyword, it will be smooth. In this way, the first sentence can be considered to be a Java ratio, because the method is default, the second sentence is mainly and the C ratio]. However, interest may be disadvantage. And the default ignore Final modifier in Java [Translation: Final keyword can be used in Java, lock the method, equivalent to the case of the Virtual keyword modification method / member function in C # / C ] and C am default Ignore the Virtual modifier compared to the provision of the Options in Java [Translation: 即 虚] Make your program slightly minimally lost some efficiency, and in C , it may hinder the scalability, although this is the realization of the base class, It is unpredictable.
12. Interface
The interfaces in the C # and the interfaces in Java are almost, but there is a greater flexibility. Classs can be explicitly explicitly implemented: public interface iteller
{
Void next ();
}
Public Interface IITERATOR
{
Void next ();
}
Public Class Clark: Iteller, Iiterator
{
Void iteller.next () {}
Void Iiterator.next () {}
}
This brings two benefits to the class that implements the interface. First, a class can achieve several interfaces without having to worry about naming conflicts. Second, if a method is useless to general users, the class can hide the method. Explicitly implementation of the method of calling the class [translation: should be the object] to the interface:
Clark Clark = New CLARK ();
(Iteller) .next ();
13. Version Processing
Solution The problem has become a main consideration of the .NET framework. Most of these considerations are reflected in the composition. In C #, the ability to run different versions of the same assembly in the same process is impressive.
When the new version of the code (especially .NET library) is created, C # can prevent software from failing. This issue is described in detail in the C # language reference. I use an example concise to explain the following:
In Java, assuming that we deploy a class called D, it is derived from a class that is called B released through the VM. The class D has a method called Foo, and it is not this method when it is released. Later, I made an upgrade for class B, now B includes a method called Foo, and the new VM is now installed on the machine using class D. Now, the software that uses D may fail, because the new implementation of class B may cause a virtual function call to D, which is an unspeakable action of a class B. [Translation: Because of the default in Java] In C #, the Foo method of class D should be declared as an Override modifier (this truly a programmer's willingness), so I know how to let class D Foo method hides the FOO method of class B, not to overload it.
Quote C # Reference Manual is a meaning "C # processing version problem is achieved by developers to clarify their intentions". Although using Override is an expression intent, the compiler can also generate - by checking if the method is checked (not a declaration) overloaded. This means that you can still have the same language like Java (Java does not need Virtual and Override keywords) and still handle version issues correctly.
See the field modifier part.
14. Parameter modifier
(1) REF parameter modifier
C # (compared to Java) allows you to pass parameters as reference. The most obvious example describing this is a universal exchange method. Not only C , not only when the statement is notified, add the Ref indicator when calling: [Translation: Don't misunderstand this sentence, C is just no Ref keyword]
Public Class Test
{
Public static void main ()
{
INT A = 1;
INT B = 2;
SWAP (Ref A, REF B);
}
Public Static Void SWAP (Ref Int A, Ref Int B)
{
INT TEMP = A;
A = B;
B = TEMP;
}
}
(2) OUT parameter modifier
The OUT keyword is a natural addition to the REF parameter modifier. The REF modifier requires parameters must be assigned before the method. The OUT modifier is clearly explicitly assigned to the parameter when the method returns. (3) Params parameter modifier
Params modifiers can be added to the last parameters of the method, and the method will accept any number of parameters of the specified type [Decolification: In a method declaration, only one params nature is allowed]. E.g:
Public Class Test
{
Public static void main ()
{
Console.writeline (Add (1, 2, 3, 4) .tostring ());
}
Public Static Int Add (params int [] array)
{
INT SUM = 0;
Foreach (Int I in Array)
SUM = I;
Return SUM;
}
}
【Author Note: A very surprising thing when learning Java is that Java can't pass parameters as reference, although you will then want this feature, and write code when you write code. When I first read the C # specification, I often think, "They do this, don't write code without it." After the reflection, I realized that this is not a problem that some functions are useful, but more about the problem that you can do if you need anything else.
When considering how C is doing, Java is a good thing, it simplifies how the parameters are delivered. In C , the method [Demolition: C does not say that "function" or "member function"] is called the parameters and method to call through the pass value, reference, pointer [translation: for example int, int *, int &】) , Make the code unnecessary complex. C # Explicitly transfer reference, whether it is a method declaration or when it is called. It greatly reduces confusion [translation: This sentence should be so understanding: due to C syntax issues, sometimes you don't know if you use an object or an object reference, there is an example after this section], and reach and Java The same goal, but C # is more expressive. Obviously this is the main purpose of C # - it does not put the programmer circle in a circle, so that they must do something around a big bend. Remember Java? In the Java Guide, it is recommended to solve the problem of the code, you should pass an array of 1 element to save your value, or do another class to save this value.
[Translation]
#include "stdafx.h"
Class ParentCls
{
PUBLIC:
Virtual void f () {Printf ("ParentCls / T");
}
Class Childcls: Public ParentCls: 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 watch the call, I don't know the reference you use or the object, but the results are different!
Return 0;
}
】
15. Features
C # and Java compile code include information similar to the field access level. C # extends this capability, any element in the class, such as class, method, field or even independent parameters, you can compile custom information and get this information at runtime. Among here there is a very simple example of the class: [AuthorAttribute ("Ben Albahari")]
Class A
{
[Localizable]
Public String Text // [Translation: Should be public string text or public system.string text, if there is no use system in front]
{
Get {returnization;}
// ...
}
}
Java uses a pair of / ** * / and @ labels comments to include additional information for classes and methods, but this information (except @DepRecated [translation: Java1.1 and later]) is not builded into the character code. C # Using predefined features Obsolete features, the compiler can warn you, exclude waste code (就 @DepRecated), and use the Conditional feature to make conditional compile. Microsoft's new XML library use features to express the fields to be serialized into XML, which means that you can easily put a class into XML and reconstruct it again. Another proper application of features is to create a truly powerful class browsing tool. C # language specification details how to create and use characteristics.
16.switch statement
The Switch statement in C # can use integer, characters, enumeration, or (not like C or Java) strings. In Java and C , if you ignore a BREAK statement in any CASE statement, you have the danger of other CASE statements being performed. I don't think this rarely needed and easily erroneous behavior has become default behaviors in Java and C , I am also very happy to see C # will not be this.
[Translation] Because C # does not support from a CASE tag to another Case tag. You can use Goto Case or Goto Default implementation if needed]
17. Pre-defined type
C # Basic types are basically similar to Java, except for the former, there is no symbolic type. C # There is Sbyte, Byte, Short, Ushort, Int, Uint, Long, Ulong, Char, Float, and Double. The only place is that there is a 16-byte numeric type Decimal, which is 16 bytes. It can take advantage of the latest processor.
[Translation: Supplement, although Decimal takes 128 bits, but its range is much smaller than float (32-bit), Double (64-bit) is much smaller, but its accuracy is much higher than the last two, It can meet financial calculations for high precision requirements.
18. Field modifier
C # in the field modifier basically Java. In order to indicate a field that cannot be modified, C # uses const and readonly modifiers. The Const field modifier is like the Final field modifier of Java, which is compiled into a part of the IL code. The read-only field calculates the value at runtime. For standard C # libraries, this can be upgraded without destroying your deployed code.
19. Jump statement
There is no more surprising place here, which may be in addition to the notorious goto statement. However, this is different from the Basic's GOTO statement that we remember 20 years ago. A goto statement must point to a label [Demolition: GOTO statement must have to be in the scope of the tag, or in other words, only allowing the GOTO statement to transfer control to a nested scope, not to transfer control A nested domain】 or a selection branch in the Switch statement [Translation], the so-called Goto Case statement]. The use of the label is similar to the continue. The label in Java, the degree of freedom is large [Demon note: Break and Continue statement in Java can be tagged]. In C #, the GOTO statement can point to any of its scope, which refers to the same method or finally block [Demo] If the goto statement occurs within the finally statement block, the destination of the GOTO statement must also be in the same One FINALLY statement block]. The CONTINUE statement in C # and the basic equivalent in Java, but C # cannot point to a label. [Translation: Java puts Goto as a reserved word, but does not implement it]
20. Composition, namespace and access level
In C #, you can organize components (clauses, structures, entrusions, enumerations) in your source code to files, namespaces, and assemblies.
The name space is just a sweet-known honey, a dessert. For example, you don't need to write genamics.winforms.grid, you can declare the class grid and wrap it up:
Namespace genamics.winforms
{
Public Class Grid
{
// ....
}
}
For classes using Grid, you can import the [Translation: ie Using Genamics.winForms] with USING keywords without having to use its full class Genamics.WinForms.grid.
The assembly is an EXE or DLL compiled from the project file. The .NET runtime uses configurable features and version rules to create them to the assembly, which greatly simplifies deployment - no write registry, just copy the combination to the relevant directory. The assembly can also form a type boundary to solve the problem of type conflict. Multiple versions of the same assembly can coexist in the same process. Each file can contain multiple classes, multiple namespaces. A namespace can span several components. In this way, the system will achieve greater freedom.
There are five access levels in C #: Private, Internal, Protected, Internal protected and public [Translation: INTERNAL protected can also be protected in both, and there is no other combination]. Private and public and Java mei. In C #, no visiting level is private instead of package. Internal Access is confined in the assembly instead of name space (this and Java more similar). INTERNAL protected is equivalent to Java protected. Protected is equivalent to the Java's Private Protected, and it has been discarded by Java.
21. Pointer operation
In C #, the pointer calculation can be used in a method labeled a UNSAFE modifier. When the pointer points to an object that can be collected by the garbage, the compiler is forced to use the Fixed keyword to fix the object. This is because the garbage collector is recycled by moving objects. But if you use the original pointer, the object it refers to is moved, and your pointer will point to garbage. I think this is a good choice for this keyword with unsafe - it does not encourage developers to use pointers unless they really want to do this.
22. Multidimensional array
C # You can create an error array [translation: Interleave array is an array of elements as an array. The dimensions and sizes of the interleave array element can be different] and multi-dimensional arrays. Arrange arrays and Java arrays are very similar. The multi-dimensional array makes it more efficient and more accurately expressed. The following is an example of such an array: int [,,] array = new int [3, 4, 5]; // Create an array
INT [1,1,1] = 5; // [Translation] This line code is incorrect: Array [1, 1, 1] = 5;]
Use interlace arrays:
int [] [] [] array = new int [3] [4] [5]; // [Translation: This line code is incorrect, should be: int [] [] [] array = new int [3] [ ] [];]
INT [1] [1] [1] = 5; [Translation: This line code is incorrect: Array [1] [1] [1] = 5;] [Translation: Carefully use interlaced array]
If the structure is combined with the structure, the high efficiency provided by C # makes an array a good choice in the field of graphics and mathematics.
23. Constructor and sectors
You can specify an optional constructor parameter:
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 [i] = i; } } The sectors are named using a naming agreement of C , using ~ symbols. The destructor can only be applied to the reference type, the value type is not available, and it cannot be overloaded. The destructor cannot be explicitly called because the life of the object is controlled by the garbage collector. Before the memory occupied by the object, each sectator in the object inheritance hierarch will be called. Although the N is naming, the destructor in C # is more like a Finalize method in Java. This is because they are all called by the garbage collector instead of being called by the programmer. Moreover, it is like a Finalize of Java, which cannot be guaranteed to be called in various situations (this often makes everyone feel shocked). If you are accustomed to adopting a certainty-based programming mode (you know when you are called), you must adapt to this different programming model when you transfer to Java or C #. Microsoft is recommended and implemented, running through the entire .NET framework is Dipose mode. You want to define a Dispose () method for classes that need to manage external resources such as graphic handle or database. For distributed programming, the .NET framework provides an agreed basic model to improve the reference count of DCOM. 24. Controlled Environment The [C # / IL code / CLR] and [Java / byte / JVM] are inevitable is just right. I think the best way is to first figure out why these technologies come. Write programs with C and C , which is generally compiled into assembly language code, which can only run on a particular processor and a specific operating system. The compiler needs to know the target processor because the different processor instruction sets are different. The compiler also knows the target operating system because different operating systems are different from the concept of how to implement work and how to implement these basic C / C . C / C This model has achieved huge success (most software you are using may be compiled), but there is also its limitations: l Programs have rich interfaces to interact with other programs (Microsoft COM is Created in order to overcome this restriction) l Programs cannot be distributed in the form of cross-platform l Can not perform program limitations in a safe operation In order to solve these problems, Java has used SMALLTALK to compile into a zona code, run in the virtual machine. The basic structure of the bytecode maintained before being compiled. This makes the Java programs and other programs to make a variety of interactions. The bytecode is also machine neutral, which means that the same Class file can run in different platforms. Finally, the fact that the Java language has no explicit memory operation (by pointer) makes it very suitable for writing "Sandbox". The initial virtual machine uses the interpreter to convert the byte code instruction stream into machine code. But this process is slowly terrible so that there is never attractive for programmers who focus on performance. Today, most JVMs use the JIT compiler, basically compiled into machine code - before and before the range of the class framework. Before it runs, it is possible to convert Java programs to assembly languages to avoid startup time and instant compiled memory burden. This process does not need to remove the runtime dependence compared to compiling Visual C programs. Java runtime (this term is hidden under the term Java virtual machine) Many critical aspects of handling procedures, such as garbage collection and security management. It is also considered to be a controlled execution environment at runtime. Although the terminology is ambiguous, despite the unused interpreter, the .NET basic model is also described above. Important improvements in .NET will come from the improvement of IL itself. Java can match the only way to modify the bytecode specification to achieve strict compatibility. I don't want to discuss these improvements, which should be left to those developers who know both bytecles and understand the IL code. 99% of the developers like me did not intend to study the IL code specification, which lists some IL design decisions that intend to improve bytecodes: l Provides better type neutral (help to implement templates); l Provides better language; l It is always compiled into assembly language before execution, never explain; l You can add additional declarative information to classes, methods, and the like. See 15. Features; At present, the CLR also provides multi-operating system support, but also provides better interoperability for JVM in other areas. See 26. Interoperability. 25. Library Language If there is no library, it is not used. C # is known without the core library, but it uses the library of the .NET frame (some of them use C # created). This article focuses on the specialty of the C # language, not .NET, it should be an illustration. Simply put, .NET library includes rich threads, collection, XML, ADO , ASP , GDI , and Winform libraries [translation: now these have become .Netj]. Some libraries are cross-platform, some dependent on Windows, please read the next paragraph about platform support. 26. Interoperability I think the interoperability is divided into three partial discussion is relatively suitable: DE, and for those pursuit of 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 long short. (1) Language interoperability The ability to integrate with other languages is only the difference between integration and difficulty. JVM and CLRs allow you to write code in multiple languages, as long as they compile into one-by-line code or IL code. However, .NET platform has a lot of work - not only the code written in other languages is compiled into an IL code, but it also makes a variety of languages to freely sharing and extending each other libraries. For example, Eiffel or Visual Basic programmers can import C # classes, overload their virtual methods; C # objects can also use Visual Basic Method (Polymorphism). If you are suspected, VB.NET has been upgraded, which has a modern object-oriented property (paying and loss of VB6 compatibility). The language written for .NET is usually inserted into the Visual Studio.NET environment. If necessary, you can use the same RAD framework. This overcomes the impression of "second-class citizens" using other languages. C # provides P / Invoke [Translation: Platform Invocation Service, Platform Call Service], more simple (no DLL) than Java's JNI and C code. This feature is very like J / Direct, the latter is a characteristic of Microsoft Visual J . (2) Platform interoperability In general, this means operating system interoperability. But in the past few years, the Internet browser itself has become more and more like a platform. C # code runs in a controlled execution environment. This is an important step that makes C # can run on different operating systems. However, some .NET libraries are Windows based, especially WinForms libraries, which depends on how much woors' Windows API. There is a transfer from the Windows API to the UNIX system, but there is no startup yet, and Microsoft has not clearly implied. However, Microsoft did not ignore the platform interoperability. The .NET library provides extension capabilities to write HTML / DHTML solutions. For clients that can be implemented with HTML / DHTML, C # /. Net is a good choice. For projects that need to be more complex across platforms, Java is a good choice. One version of Kylix-Delphi, allowing the same code to be able to compile on Windows, perhaps 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 # can be accessed. Because Microsoft has a great role in developing these standards, their support for these standards is in a very favorable location. They will certainly provide less standard support because of commercial motives (I don't say it is justified) - for things that compete - such as Corba (Com compete) and OpenGL (DirectX's competitors). Similarly, Sun's commercial motive (once again, I don't say that they are justified) means that Java will not do their best to support Microsoft standards. Since the C # object is implemented as a .NET object, it is automatically exposed to a COM object. C # therefore can expose both COM objects or COM objects. This way, you can integrate COM code and C # items. .NET is a framework that can eventually replace COM - but there is already so many deployed COM components, I believe that inequality .NET replaces COM, which has been replaced by the next wave technology. But in any case, I hope that .NET can have a long and interesting history! J27. Conclusion So far, I hope that I have given you a C # and Java, C in conceptual comparison. Overall, compared to Java, I believe that C # provides better expression and more suitable for writing code for performance, which also has Java's elegance and simple, which is also more attractive than C . Place of strength. - Full text -