A comparative Overview of C # Chinese version (ii)

Source: Internet
Author: User
Tags foreach final integer reflection wrapper advantage
In Gametest, we created a game and a referee to monitor game, and then we changed game's score to see how referee reacted to it. In this system, game has no knowledge of referee, and any class can listen and respond to game score changes. The keyword event hides all delegate methods except + = and =. These two operators allow you to add (or remove) multiple event handlers that handle the event.
Our following example illustrates the meaning of the latter remark:
public class Game
{
public event Scorechangeeventhandler Scorechange;
protected void Onscorechange ()
{
if (scorechange!= null) Scorechange (ref true);//Within the class, you can use the
}
, but outside of this class, Scorechange can only appear to the left of the operator + = and =.
You may first encounter this system in the graphical user interface framework. Game is like a control in the user interface that triggers events based on user input, and referee is similar to a form that handles the event.
Author Note: The first time a delegate was introduced by Microsoft Visual J + + was also designed by Anders Hejlsberg, and it was one of the causes of the technical and legal disputes between sun and Microsoft. James Gosling,java's designer, Anders Hejlsberg once had a false modesty sound also humorous comments, said he because and Delphi entangled feelings should be called him "method pointer". After studying Sun's argument over the Commission, I think it seems fair to call Gosling "Everything is a gentleman". In the past few years, in the programming world, "the abstraction that makes an effort to simulate reality" has been replaced by many people. "Reality is object-oriented, so we should simulate it with object-oriented abstraction."
The debate between Sun and Microsoft on commissioning can be seen here:
http://www. Javasoft.com/docs/white/delegates.html http://msdn.microsoft.com/visualj/technical/articles/delegates/truth.asp 】
6. Enumeration
Enumeration enables you to specify a set of objects, such as:
Statement:
Public enum Direction {North, East, West, South};
Use:
Direction wall = Direction.north;
It's an elegant concept, and that's why C # decides to keep them, but why does Java choose to abandon it? In Java, you have to do this:
Statement:
public class Direction
{
Public final static int north = 1;
public final static int = 2;
Public final static int west = 3;
Public final static int SOUTH = 4;
}
Use:
int wall = Direction.north;
It looks like the Java version is more expressive, but that's not the case. It is not type-safe, and you may accidentally assign any value of int to wall and the compiler does not make any complaints. "You obviously can't write this: Direction wall = Direction.north;". Frankly speaking, in my Java programming experience, I have never spent too much time writing something extra to catch errors because of the type of security that is not in place. But it's a pleasure to have enumerations. One of the surprises that C # brings to you is-when you debug a program, if you set a breakpoint where you use an enumeration variable, the debugger automatically translates the direction and gives you a readable message instead of a value that you have to decipher yourself:
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 an if statement, you will get a direction that you can read instead of a value of 5.
A change in this example will help to understand more:
Statement:
public enum Direction {north=1, east=2, west=4, south=8, middle = 5/* Note here Code/};
Use:
Direction Direction = Direction.north | Direction.west;
if ((Direction & Direction.north)!= 0)
//....
If you set a breakpoint on an if statement, you will get a direction (ie middle) that you can read instead of the value 5 "
The author note: The reason that enumerations are discarded by Java is most likely because it can be replaced with classes. As I mentioned above, using a class alone is not a good way to express an attribute as well as other concepts. What is the advantage of the philosophy of Java, if it can be handled by class, without introducing a new structure? The biggest advantage to look at is simplicity-a shorter learning curve and no need for programmers to think about doing the same thing in many ways. In fact, the Java language improves C + + in many ways, such as no pointers, no header files, and a single object hierarchy. The common denominator of all these simplifications is that they actually make programming-well-simple, but without the enumerations, attributes, events, and so on that we've just mentioned, it makes your code even more complicated.
7. Collection and foreach statements
C # provides a shortcut to a for loop, and it also facilitates a more consistent collection class:
In Java or C + +:
1. while (! Collection.isempty ())
{
Object o = Collection.get ();
Collection.next ()
//...
2. for (int i = 0; i < array.length; i++)
//...
In C #:
1. foreach (Object o in collection)
//...
2. foreach (int i in array)
//...
C # 's For loop will work on the collection object (the array implements a collection). The collection object has a GetEnumerator () method that returns a enumerator object. The enumerator object has a MoveNext () method and a current property.
8. Structure
It's better to think of C # 's structure as making the language's type system more elegant and not just a concept that "can be used to write really efficient code if you need to."
In C + +, structs and classes (objects) can be allocated on stacks or heaps. In C #, structs are created on the stack forever, and classes (objects) are always created on the heap. Using structs can actually generate more efficient code:
public struct Vector
{
public float direction;
public int magnitude;
}
vector[] vectors = new Vector [1000];
This allocates 1000 vectors to a single space, which is much more efficient than declaring vectors as classes and using a for loop to instantiate 1000 independent vectors. "Because of the suspicion that the original is wrong, this intentionally omitted a sentence, but should not affect your understanding of this section of the content":
int[] ints = new ints[1000];//"The code here is wrong, should be int[] ints = new int[1000];"
C # completely allows you to extend the set of basic types built into languages. In fact, all the basic types of C # are implemented in a structured way. int is simply an alias for the System.Int32 structure, long is just an alias for the System.Int64 structure, and so on. These basic types of course can be specifically handled by the compiler, but the language itself does not differ. "It means that the language itself provides a consistent way of handling all types." In the next section, we can see how C # is doing this.
9. Consistent type
Most languages have basic types (int, long, and so on). Advanced types are ultimately composed of basic types. It is usually useful to handle basic and advanced types in the same way. For example, it is useful if a collection can contain int as inclusive sting. To do this, Smalltalk deals with int and long by sacrificing some efficiency like a string or form. Java attempts to avoid this loss of efficiency by handling basic types like C and C + +, but also by providing the corresponding wrapper class for each basic type-int wrapped as a double for integer,double. C + + template parameters can accept any type, provided that the type provides an implementation of the operations defined by the template.
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 wording is wrong:
int I = new int (1);
Integer iobj = 1;

C # provides a different solution to the problem. In the previous section, I introduced the structure in C #, pointing out that the basic type is just an alias to the structure. Since structs have methods owned by all object types, that code can be written like this:
int i = 5;
System.Console.WriteLine (i.ToString ());
If we imagine using a struct like an object, C # will box the structure for you, and when you need to use the structure again, you can do it by unpacking:
Stack stack = new stack ();
Stack. Push (i); Packing
int j = (int) stack. Pop (); Split Box
Unpacking is not only the need for type conversions, it is also a way to seamlessly handle the relationships between structs and classes. You have to be clear. Boxing is done to create a wrapper class, although the CLR can provide additional optimizations for the boxed object.
It can be argued that in C #, for any value (struct) type, there are the following wrapper classes:
Class T_box//t represents any value type
{
T Value;
T_box (T t) {Value = t;}
}
When boxing, for example:
int n = 1;
Object box = N;
The concept is equivalent to:
int n = 1;
Object box = new Int_box (i);
When unpacking a box, for example:
Object box = 1;
int n = (int) box;
The concept is equivalent to:
Object box = new Int_box (1);
int n = ((Int_box) Box). Value; "
Author Note: C # designers should consider templates during the design process. I suspect there are two reasons why templates are not used: The first is chaos, templates can be difficult to integrate with object-oriented features, and it brings too many (confusing) design possibilities for programmers, and it's hard to work with reflection; 2nd, If. NET libraries (such as collection classes) do not use templates, the templates will not be useful. But, indeed. NET classes use them, there will be more than 20 kinds of use. NET class language has to be able to work with templates, which is technically very difficult to achieve.
It is interesting to note that the template (generics) has been considered by the Java community to be incorporated into the Java language specification. Perhaps each company will sing each of the tune-sun said. NET suffers from the lowest common denominator syndrome, while Microsoft says "Java does not support multiple languages."
(August 10) Read an interview with Anders Hejlsberg (http://windows.oreilly.com/news/hejlsberg_0800.html), feeling as if the template had surfaced on the horizon, but the first edition did not, It is because of all the difficulties we have mentioned above. It is interesting to see that the IL specification is written so that the Il code can show the template (in a non destructive way so that reflection works well). Here, I give a link to the Java community to consider adding generics: http://jcp.org/jsr/detail/014.jsp "
Here is the link to the Chinese version of the Anders Hejlsberg interview mentioned above: Http://www.csdn.net/develop/article/11/11580.shtm. In addition, for more information on generic programming, see the links here: http://www.csdn.net/develop/article/11/11440.shtm "

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.