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]
This article will provide new programming methods provided in C # and how it improves two neighbor-Java and C . C # In many ways and Java use a similar way to improve C . Therefore, I don't intend to repeat things such as the advantages of a single object level. The body will begin with the similarity of C # and Java, and then focus on the new characteristics of C #.
background
In June 2000, Microsoft announced a new programming language called C #. C # is a great-oriented language-oriented language that combines simple, expressive, and performance. The .NET platform is run in public language (similar to Java virtual machine) and a variety of languages (they can work together by compiling into intermediate languages). C # and .NET have some of the characteristics and .Net collaboration of C #, vice versa (although .NET's goals are well collaborated with many languages). This article is mainly concerned about C #, but it will be occasionally mentioned .NET. The design of C # draws on a variety of languages, but the main thing is Java and C . It is designed by Anders Hejlsberg (Ding Ding Delphi [Ding Ding Delphi [Made Object Pascal More Some] Language Designers) and Scott Willing.
table of Contents
1. C # and Java
2. Attributes
3. Indexer
4. Delegate
5. Incident
6. Enumerate
7. Collection and Foreach statement
8. Structure
9. Type
10. Operator overload
11. Polymorphism
12. interface
13. Version processing
14. Parameter modifier
15. Characteristics [Translation], attribute, I am in the "C # Chief Designer Anders Hejlsberg Interview" (see 9CBS http://www.9cbs.net/develop/Article/11580.shtm) has said that now So, the term is still more confusing, and even the Property is not divided, it is translated as "attribute" (Visual Studio.net 7.0 Beta 2 online documentation). However, in this article, it is still translated into "characteristics" to distinguish between
16. Select statement
17. Predefined type
18. Field modifier
19. Jump statement
20. Composition, namespace and access level [Translation] Assembly word translation is more chaotic, some translated as "accessories", some translated as "components", some translated as "assembly", and Visual Studio.net 7.0 The Beta2 online documentation is translated into "assembly". From the technical statement, this translation says it is very fact, but the total feeling and the appearance of this word are far apart, and before the translation is not uniform, this article is temporarily translated as "" Combination "] 21. Pointer operation
twenty two. Multi-dimensional array [translation: This section also talks about interleave arrays]
twenty three. Constructor and sectors
twenty four. Controlled execution environment
25. Library
26. Interoperability
27. in conclusion
1.c # and java
Below is a list of characteristics common in C # and Java, which is to improve C . Although these features are non-culturally focused, it is important to understand the similarities between them.
l Compile as machine independent, language independent code, running in a controlled execution environment;
l Take the garbage collection mechanism while eliminating the pointer (C #, the pointer is limited to the code specified in the code ";
l Powerful reflexibility;
l There is no header file, all the code is in the package or assembly, there is no loop dependence of class declarations;
l All classes are derived from Object, and must be allocated on the pile with the new keyword; [translation: java is Object; C # is Object, equivalent to .NET system.Object]
l When you enter the label / synchronous code, you can support multi-threads by locking on the object; [Translation: For example, in Java, you can use the Synchronized keyword in Java, you can use the Monitor class, Mutex class, LOCK statement in C # and many more】
l Interface support - multi-inheritance interface, single inheritance implementation;
l internal class;
L-class inheritance does not need to specify an access level; [Translation: In C , you can do this: Class CLS2: Private CLS1 {}; etc
l No global function or constant, everything must be class;
L array and strings save length records with boundary inspection capabilities;
l Always use "." operator, no longer "->", "::" operator;
l Null and Boolean / Bool are keywords; [translation: boolean in java, C # is Bool, equivalent to system.boolean]
l All values must be initialized before use;
l If statement cannot use integer numbers as discriminant conditions;
l After the TRY sentence, you can follow the Finally clause. [Translation: Standard C is not, but Visual C has expanded SEH, you can use __try and __finally]
2. Attribute
For users of Delphi and Visual Basic, attribute is a familiar concept. The purpose of the use of properties is to formally format the concept of acquired / setter [translation: original to getTer / setter], which is a widely used mode, especially in the RAD (fast application development) tool. The following is a typical code you might write in Java or C :
Foo.setsize (getSize () 1);
Label.Getfont (). setBold (true);
The same code may become in C #:
Foo.size ;
Label.Font.Bold = true;
C # code is more intuitive and readable for users who use foo and label. In terms of realization, it is almost equivalent:
Java / C :
Public int getSize ()
{
Return size;
}
Public void setsize (int value)
{
SIZE = Value;
}
C #:
Public int size
{
Get {returnide;}
SET {size = value;}
}
Especially for readable and writable properties, C # provides a more refreshing way to handle this concept. In C #, the GET and SET methods are inherent, and people are maintained in Java and C . There are many advantages in the processing method of C #. It encourages programmers to think about attribute - labeled this property to be readily writable and who is more natural? Or should not be attribute at all? If you want to change your properties, you can check one (I have seen the acquisition unit and setup device of several hundred lines of code in the middle "[translation note: here refers to C (Java) The same data member / field (generally said) acquisitioner and settinger]). Note As long as you can, this also avoids the problem of each other. IDE [Translation: Integrated Development Environment] can help do this (in fact, I suggest them do this [translation: "they" should refer to Microsoft related personnel]), but should keep in mind a basics on programming Principle - try to do the abstraction of the simulation of our problem space. A language that supports properties will help achieve better abstraction.
【Author Note: An opposition to this advantage of attributes believes: When using this grammar, you can't do it in a field or attribute. However, in Java (of course, it also includes C #), almost all of the true complex classes do not have the field of public. Fields generally have only as little access level as possible (the default) defaults defined by private / protected, or language, and only through the acquisitioner and setter method, which means you can get a beautiful syntax. Let the IDE parsing code is also fully feasible, can highlight the properties in different colors, or provide code completion information to indicate whether it is an attribute. We should also see that if a class design is good, this class user will only care about the interface (or specification) of the class. [Translation: This is open to its customers (not only public, " For example, it is also a protected method, attribute (C / Java no significant property concept), etc. The clients here include their derived classes, etc., rather than their internal implementation. Another possible argument is that attribute is not effective enough. In fact, a good compiler can return only a field of acquired acquisition, which is as fast as the direct access field. Say, even if you use the field to be valid than the acquired / setup device, use the properties and the following benefits - in the future, you can change the field of the property. The fields operated in the device / setup can also be used in the acquisition device / setup, and does not affect the code that relies on this property] 3. Indexer
C # can be processed like an array by providing an indexer. Especially attributes, each element is exposed in a GET or SET method.
Public Class Skyscraper
{
Stories;
Public story this [int index]
{
get
{
Return Stories [index];
}
set
{
IF (value! = null)
{
Stories [index] = value;
}
}
}
// ...
}
Skyscraper EmpireState = New Skyscraper (/ *.../);
EmpireState [102] = New Story ("Top One", /*...*/);
[Translation: The biggest benefit of the indexer is to make the code look more natural, more in line with the actual thinking mode]
4. Entrusted
The commission can be considered a type of security, object-oriented function pointer, which can have multiple methods. The issue of delegate processing can be handled in C , and the interface can be handled in Java. It improves the function pointer mode by providing type security and supporting multi-way; it improves the interface by making method calls without requiring internal class adapters or additional code to process multi-method call issues. The most important use of commission is that the event is handled. The next section will be introduced by an example.
5. Event
C # provides direct support for events. Although event processing has always been the basic part of programming, it is surprising that most languages have made efforts to format this concept. If you look at how the mainstream framework is handled, we can mention the following example: Delphi's function pointer (called closed bag) and Java's internal class adapter, of course, there is also a Windows API message system. C # provides a refreshing event processing scheme using the Delegate and Event keywords. I think the best way to describe this mechanism is to give an example to illustrate the process of declaring, trigger, and handling events:
// The delegate declaration defines the method signature that can be called [Translation note: The signature here can be understood as "prototype"] Public Delegate Void ScorechangeEventHandler (Int Newscore, Ref Bool Cancel);
// Class-generating an event
Public Class Game
{
// Note Use Keywords
Public Event ScorechangeEventHandler Scorechange;
int score;
// Property SCORE
Public int score
{
get
{
Return score;
}
set
{
IF (Score! = Value)
{
Bool Cancel = False;
Scorechange (Value, Ref Cancel);
IF (! ca Zancel)
Score = value;
}
}
}
}
// Treat the class
Public Class Referee
{
Public Referee (Game Game)
{
/ / Monitor the score change in GAME
Game.scorechange = new scorechangeeenthandler (game_scorechange);
}
// Note this method signature and scorechangeeeventhandler method signature to match
Private void game_scorechange (int newscore, ref boce)
{
NewsCore <100)
System.console.writeline ("Good Score");
Else
{
CANCEL = True;
System.console.writeline ("No Score Can Be That High!");
}
}
}
// Test class
Public Class Gametest
{
Public static void main ()
{
Game game = new game ();
Referee Referee = New Referee (Game);
Game.score = 70; // [Translation: Output Good Score]
Game.score = 110; // [Translation] Output No Score Can Be That High!]
}
}
In GameTest, we have created a Game and a surveillance GAME, then then we change the Game's score to see where Refere is backed. In this system, Game does not have any knowledge of Refree, and any class can monitor and react with the GAME's score. Keyword EVENT hides all entrustment methods other than = and - =. These two operators allow you to add (or remove) multiple event processors for processing the event.
[Translation: We will explain the words of the following example:
Public Class Game
{
Public Event ScorechangeEventHandler Scorechange;
protected void onscorechange ()
{
IF (scorechange! = null) scorechange (30, ref true); // can be used in the class
}
But in this class, scorechange can only appear in the left side of the operator = and - =
You may first encounter this system in the Graphical User Interface Framework. GAME is like a control of the user interface, which is triggered according to the user input, and Refree is similar to a form, it is responsible for processing the event. 【Author Note: Entrusted the first time by Microsoft Visual J is also designed by Anders Hejlsberg, and it is also one of the causes of Sun and Microsoft disputes in technology and legal. James Gosling, Java designer, has a good commentary for Anders Hejlsberg, and said that he is also a hobby, saying that he should call him "Method of Methods" because he and Delphi have broken silk. After studying Sun's dispute, I think Gosling is "everything is a class." It seems to be fair. In the past few years, in the programming industry, "doing efforts to simulate realistic abstraction" has been recorded by many people. Taking the "realistic is object-oriented, so we should use object-oriented abstraction to simulate it."
Sun and Microsoft's debate about the commission can be seen here:
Http://www.javasoft.com/docs/white/delegates.html http://msdn.microsoft.com/visualj/technical/th.AS /DELEGATES/TRUTH.ASP]
6. Enumeration
Enumerates you can specify a set of objects, for example:
statement:
Public Enum Direction {North, EAST, WEST, SOUTH};
use:
Direction Wall = Direction.North;
This is really an elegant concept, which is also C # why it will decide why they have, but why Java has chosen to abandon? In Java, you have to do this:
statement:
Public Class Direction
{
PUBLIC FINAL static int north = 1;
Public final static int east = 2;
Public final static int west = 3;
Public final static intang = 4;
}
use:
Int wall = direction.north;
It seems that the Java version is more expressive, but the fact is not the case. It is not type of security, you may accidentally assign any int type value to the WALL and the compiler will not issue any complaints [Translation: You obviously can't write: Direction Wall = Direction.North;]. Frankly, in my Java programming experience, I have never spent too much time because of non-type safety, I have written some extra things to capture errors. However, it is a quick thing to have an enumeration. C # A surprise that brings you is - when you debug the program, if you set a breakpoint in the place where the enumeration variable is used, the debugger will automatically translate Direction and give you a readable information, not one you don't have. Number of do not rectify:
statement:
Public enum direction {north = 1, EAST = 2, West = 4, South = 8};
use:
Direction Direction = DIRECTION.NORTH | DIRECTION.WEST;
IF ((Direction & Direction.North)! = 0)
// ....
If you set a breakpoint on the IF statement, you will get a Direction you read and not a value of 5.
[Translation: This example is changed, it will help understand: declaration:
Public enum direction {north = 1, EAST = 2, West = 4, South = 8, Middle = 5 / * Note this code * /};
use:
Direction Direction = DIRECTION.NORTH | DIRECTION.WEST;
IF ((Direction & Direction.North)! = 0)
// ....
If you set a breakpoint on the IF statement, you will get a Direction (ie, middle) instead of value 5]
【Author Note: The reason for enumeration is abandoned by Java may be because it can be replaced by a class. As I mentioned above, use the class, we can't express a certain feature like other concepts. Java's "If it can be handled by class, what is the advantage of the philosophy of a new structure? The biggest advantage is simple - shorter learning curves, and there is no need to consider multiple ways to do with the same thing. In fact, Java language has improved C in many ways, such as without pointers, no header files, and single object hierarchy. All of these simplified commonality is actually programming - - simple, but without the enumeration, attributes, events, properties and events mentioned just mentioned, but instead make your code more complicated]
7. Collection and Foreach statement
C # provides a shortcut for a for loop, and it also promotes more consistent collection:
In Java or C :
WHILE (! Collection.Isempty ())
{
Object o = collection.get ();
COLLECTION.NEXT ()
// ...
2. for (int i = 0; i // ... In C #: FOREACH (Object O in Collection) // ... 2. Foreach (Int I in Array) // ... The C # FOR loop will work on the collection object (a collection implementation). The collection object has a getENUMERATOR () method that returns an ENUMERATOR object. ENUMERATOR object has a MoveNext () method and a Current property. 8. Structure The structure of the C # is considered to make the language type system is more elegant rather than a "if you need it, you can use it to write a truly efficient code" more better. In C , structures and classes (objects) can be allocated on stacks or piles. In C #, the structure is always created on the stack, and the class (object) will always be created on the heap. The use structure can actually generate more efficient code: Public struct vector, PUBLIC STRUCTOR { Public Float Direction; Public int magnitude; } Vector [] vectors = new vector [1000]; This will allocate 1000 VECTORs on a space, which is more efficient than we declare the Vector as class and use for loops to instantiate 1000 separate vectors. [Translation: Due to the income of the original text, he deliberately leaked a sentence, but should not affect your understanding of this section]: Int [] INTS = new INTS [=] 【:: This code is incorrect, it should be int [] INTS = new int [1000];] C # fully allows you to extend the basic type of built-in in the language . In fact, all basic types of C # are implemented in a structural manner. INT type is just the alias of the SYSTEM.INT32 structure, and the long type is just the alias of the System.InT64 structure. These basic types can of course be specially processed by the compiler, but the language itself does not distinguish [translation: means that the language itself provides a consistent method for processing all types). In the next section, we can see how C # is doing this. 9. Coincidence Most languages have basic types (INT, long, etc.). Advanced types are ultimately constructed from basic types. It is usually used in the same way that the basic types and advanced types are usually used. For example, if a collection can be used in an inlinest, Int is useful. To this end, SmallTalk processes int and long through the sacrificing efficiency like processing String or Form. Java tries to avoid this efficiency loss, and it handles the basic type like C and C , but also provides the corresponding packaging class -int package for each basic type to INTEGER, Double package is Double. The C template parameter accepts any type as long as this type provides the implementation of the operation of the template definition. [Translation: In Java, you can write this: INT i = 1; Double D = 1.1; Integer IOBJ = New Integer (1); Double dobj = new double (1.1); The following means is wrong: INT I = New Int (1); Integer IOBJ = 1; 】 C # provides a different solution to this problem. In the previous section, I introduced the structure in the C #, pointing out that the basic type is just an alias for the structure. Since the structure has a method of all object types, that code can be written: INT i = 5; System.console.writeline (i.tostring ()); If we imagine a structure, use a structure, C # will be able to pack this structure as an object, when you need to use a structure again, you can implement: Stack stack = new stack (); Stack.push (i); / / Packing INT j = (int) stack.pop (); // Unbo The unpacking is not only the need for type conversion, but it is also a way of seamless processing structure and classes. You have to clear the boxes to do work for creating packaging classes, although CLR can provide additional optimization for the boxed object. [Translation: It can be so much, in C #, for any value (structure) type, there is a packaging class: Class T_box // t represents any value type { T value; T_box (t t) {value = t;} } When packing, for example: INT n = 1; Object box = n; Conceptual equivalent: INT n = 1; Object Box = new int_box (i); When the box is removed, for example: Object Box = 1; INT n = (int) box; Conceptual equivalent: Object Box = new int_box (1); INT N = ((int_box) box) .value;] 【Author Note: The designer of C # should consider the template during the design process. I doubt that there are two reasons why they have not been used: the first is confusion, the template may be difficult to integrate with object-oriented features, which has brought too many (confusing) design possibilities for programmers, and it is very It is difficult to work together; the second point is that if the .NET library (such as a collection class) does not use the template, the template will not be too useful. However, fruit. Net class uses them, there will be more than 20 languages that use .NET classes to work with templates, which is technically very difficult to implement. Noting that template (generics) has been considering the Java community in the Java language norms. Perhaps each company will sing all-in-SUN say ".NET has the least common bobics", and Microsoft said "Java does not support multi-language". (August 10th apologized) After reading an interview with Anders Hejlsberg (http://windows.ore.com/news/hejlsberg_0800.html), I feel that the template has floated the horizon, but the first edition is not, The difficulties we mentioned above. See the IL specification is such that the IL code can display templates (with a non-destructive way to make reflexes can work well) and the bytecode can not be a very interesting thing. Here, I also gave a link to the Java community to consider adding generics: http://jcp.org/jsr/detail/014.jsp] [Translation: Here is the Chinese version of the above mentioned above to Anders Hejlsberg: http://www.9cbs.net/develop/Article/11/11580.SHTM. Also, if you want to know more about generic programming knowledge, see the link here: http://www.9cbs.net/develop/Article/11/11440.shtm】