A comparative Overview of C # Chinese version (i)

Source: Internet
Author: User
Tags arrays bool execution garbage collection inheritance int size new features visual studio
Chinese A Comparative Overview of C # Chinese version (last article)
Author: Ben Albahari
Company: Genamics
Date: July 31, 2000 first edition, August 10, 2000 revision.
Thank the following people for their support and feedback (alphabetical order): Don Box, C.R Manning, Joe Nalewabau, John Osborn, Thomas Rhode & Daryl Richter.
Translator: Glory
"Preface: C # Introductory Classic!" Hope that the text for beginners will not affect the fluency of reading. Limited to the translator's time and ability, if there are corruption in the text, the original English will prevail.

This article will be based on the new programming method provided by C # and how it improves the two neighboring-java and C + + as the center. C # in many ways and Java in a similar way to improve C + +. So I'm not going to repeat things like the merits of a single root object hierarchy. The body begins with a summary of C # and Java similarities, and then focuses on the new features of C #.
background
June 2000, Microsoft announced at the same time. NET platform and a new programming language called C #. C # is a very good combination of simple, expressive, performance-oriented, strongly typed object-oriented language. NET platform is centered on a common language runtime (similar to a Java Virtual machine) and a library that can be shared by multiple languages, which can be compiled into intermediate languages to work together. C # and. NET have a little symbiotic relationship with some of the features and-c#. NET collaboration is good, and vice versa (though. NET's goal is to collaborate well with multiple languages. This article focuses on C #, but occasionally mentions. NET as needed. C # is designed to draw on a variety of languages, but the main thing is Java and C + +. It was designed by Anders Hejlsberg (the famous Delphi "" Language designer) and Scott Wiltamuth, which is more appropriate for the object Pascal.
Directory
1. C # and Java
2. Property
3. Indexing device
4. Commissioned
5. Event
6. Enumeration
7. Collections and foreach statements
8. Structure
9. Type consistent
10. Operator overloading
11. Polymorphic
12. Interface
13. Version processing
14. Parameter modifiers
15. attribute, I said in the translation of "C # chief designer Anders Hejlsberg" (see Http://www.csdn.net/develop/article/11/11580.shtm of CSDN) So far, the translation of the word is still more confusing, even with property, and is translated as "properties" (this is the case with Visual Studio.NET 7.0 Beta 2 online documentation). However, in this article, it is still translated into "characteristics" to differentiate "
16. SELECT statement
17. Predefined types
18. Field modifiers
19. Jump statement
20. Combination, namespace and access level "assembly" translation of the word is more confusing, some translated as "accessories", some translated as "components", and some translated as "composition", and Visual Studio.NET 7.0 Beta2 online documentation is translated as "Assembly", technically speaking, This translation is true, but the general feeling and the appearance of the word far away, before the reunification of the translation method, this article is tentatively translated into "combination"
21. Pointer operations
22. Multidimensional array "In this section, we also talked about jagged arrays."
23. Constructors and destructors
24. Controlled execution Environment
25. Library
26. Interoperability
27. Conclusion
1.c# and Java
The following is a list of features common to C # and Java, designed to improve C + +. Although these features are not the focus of this article, it is important to understand the similarities between them.
L compile to Machine independent, language independent code, run in the controlled execution environment;
L Use garbage collection mechanism and discard pointers (in C #, pointers are limited to unsafe code);
L Strong reflective ability;
l have no header file, all code is in package or composition, there is no cyclic dependency problem of class declaration;
L All classes derive from object and must be assigned to the heap with the new keyword; in Java, the object in object;c# is equivalent to. Net of System.Object "
L support multithreading by adding locks to objects when entering the lock/sync code; In Java, for example, you can apply a synchronized keyword to a method, in C # you can use the Monitor class, the mutex class, the lock statement, and so on.
L interface Support-Multiple inheritance interface, single inheritance implementation;
L internal class;
L class inheritance without specifying the access level; in C + +, you can do this: class Cls2:private cls1{};
l have no global function or constant, all must belong to class;
l Arrays and strings preserve length counts and have boundary checking capabilities;
L Always use "." operator, no longer has "->", "::" operator;
L NULL and boolean/bool are keywords; "in Java in Boolean, C # for BOOL, equivalent to System.Boolean"
L All values must be initialized before use;
L If statements cannot use integer numbers as the criterion;
L A Try statement block can be followed by a finally clause. "Standard C + + is not possible, but Visual C + + has extended to SEH, you can use __try and __finally"
2. Property
Attributes are a familiar concept for users of Delphi and Visual Basic. The purpose of using attributes is to formalize the concept of the accessor/Setup [Getter/setter], which is a widely used pattern, especially in the RAD (Rapid Application Development) tool.
Here are some typical code you might write in Java or C + +:
Foo.setsize (GetSize () + 1);
Label.getfont (). Setbold (True);
The same code in C # may become:
foo.size++;
Label.font.bold = true;
C # code is more intuitive and readable for users who use Foo and label. In terms of implementing attributes, it's almost as simple as this:
Java/c++:
public int GetSize ()
{
return size;
}
public void setSize (int value)
{
size = value;
}
C#:
public int Size
{
get {return size;}
set {size = value;}
}
Especially for writable properties, C # provides a refreshing way to handle this concept. In C #, the Get and set methods are intrinsic, while in Java and C + + people are needed for maintenance. C # 's approach has many advantages. It encourages programmers to think in terms of attributes-which is more natural to mark this attribute as readable and read-only? Or should it not be an attribute at all? If you want to change the name of your property, all you have to do is check it out. (I have seen the acquisition and setup of hundreds of lines of code in C + + (Java) for the same data member/field (in general) and the "accessor"). Comments can also be made in just one place, which also avoids the problem of synchronizing with each other. The IDE's "Integrated development environment" is something that can help (in fact, I suggest they do this "they" should mean Microsoft), but keep in mind a fundamental principle of programming-try to do the abstraction that simulates our problem space. A language that supports attributes will help to get a better abstraction.
Author Note: One objection to this advantage of attributes is that when you use this syntax, you don't know if you're manipulating a field or an attribute. However, in Java (and, of course, C #), almost all classes that are really complex do not have fields that are public. Fields typically have only the smallest level of access (private/protected, or default defined by language), and are exposed only through the accessor and setup methods, which means you can get a graceful syntax. It is also perfectly possible to have the IDE parse the code, highlighting the properties in different colors, or providing code completion information to indicate whether it is an attribute. We should also see that if a class is well designed, the user of this class will only be concerned with the interface (or specification) of that class. Methods, attributes (c++/) that the class exposes to its customers (not just public, but also possibly protected) Java has no explicit attribute concepts, etc., where the customer includes its derived classes, and so on "rather than its internal implementation. Another possible argument is that the attribute is not efficient. In fact, a good compiler can inline only returns a field's accessor, which is as fast as accessing a field directly. Ultimately, even if you use a field that is more efficient than the picker/setup, using attributes also has the following benefits-you can change the field of a property in the future: the implementation code that can change the accessor/setup, such as changing the field in the Picker/setup, or in the acquisition/ To do some validation or cosmetic work in the setup, etc., without affecting the code that depends on the property.
3. Indexing Device
C # By providing indexers, you can work with objects as you would an array. In particular, each element is exposed as a get or set method.
public class skyscraper
{
Story[] 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 ("The Top One",/*...*/);
The biggest advantage of the indexer is that it makes the code look more natural and more in line with the actual thinking model.
4. Entrusted
A delegate can be considered a type-safe, object-oriented function pointer that can have multiple methods. The problem of delegate processing can be handled with function pointers in C + +, while in Java it can be handled with interfaces. It improves the function pointer by providing type safety and support for multiple methods; It improves the interface by making method calls without the need for internal class adapters or extra code to handle multiple-method invocation problems. The most important use of delegates is event handling, which is described in the next section by an example.
5. The event
C # provides direct support for events. Although event handling has been a fundamental part of programming, it is surprising that most languages have done little to formalize the concept. If you look at how the current mainstream framework handles events, we can cite the following examples: Delphi function pointers (called closures) and Java internal class adapters, and of course the Windows API messaging system. C # uses the delegate and event keywords to provide a refreshing event-handling scenario. I think the best way to describe this mechanism is to give an example of the process of declaring, triggering, and handling events:
A delegate declaration defines a method signature that can be invoked. "The signature here can be understood as" prototype "
public delegate void Scorechangeeventhandler (int newscore, ref bool cancel);
The class that generated the event
public class Game
{
Note the use of keywords
public event Scorechangeeventhandler Scorechange;
int score;
Attribute Score
public int Score
{
Get
{
return score;
}
Set
{
If (score!= value)
{
bool Cancel = false;
Scorechange (value, ref cancel);
if (! Cancel)
Score = value;
}
}
}
}
Classes that handle events
public class referee
{
Public referee (Game Game)
{
Monitor the score score changes in the game
Game. Scorechange + = new Scorechangeeventhandler (game_scorechange);
}
Note that this method signature and Scorechangeeventhandler method signature should match
private void Game_scorechange (int newscore, ref bool cancel)
{
if (NewsCore < 100)
System.Console.WriteLine ("Good Score");
Else
{
Cancel = true;
System.Console.WriteLine ("No Score can be so high!");
}
}
}
Test class
public class Gametest
{
public static void Main ()
{
Game Game = new Game ();
Referee Referee = new Referee (game);
Game. Score = 70;//: Output Good Score "
Game. Score = 110;//"The output No Score can be that high!"
}
}

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.