Huashan Arigue: C # to Java
(Cactus Studio June 29, 2001) 17:01) C # (C-Sharp) is a new programming language of Microsoft, known as the first facing language in the C / C family. However, no matter what it claims, many people think that C # is more like Java's clone, or Microsoft is used to replace Java products. Is the truth like this? The comparison results of this paper show that C # is not limited to the compatriots of Java. If you are a Java developer, you want to learn C # or learn more about C # knowledge, then this article must put the initial 10 minutes. First, the language specification of C #, C and Java C # is written by Microsoft's Anders Hejlsberg with Scott Wiltamuth. In the current Microsoft Sky, it is always interesting to make C # and C , Java. Considering the current IT media's public opinion tendency, if you know that C # is closer to Java instead of C , things are not worthy of strange. For readers just added this discussion, the following table 1 makes you a judgment. Obviously, conclusions should be: Java and C # although not twin sons, C # The main features are closer to Java rather than C .
Table 1: Comparison C #, C and Java most important function Function C # C Java inheritors allow inheritance of single class, allowing multiple interfaces to allow multiple interfaces to allow inheritance of single classes, allowing implementation of multiple interface interfaces "Interface" keywords pass abstract class through "interface" keyword memory management by runtime environment management, using garbage collector needs manual management by runtime environment management, use garbage collector pointer support, but only sells very little Support in security mode. It is usually supported by reference replacement pointer, a very common function. Not supported at all. Generation is hereby incorporated by reference. Source code compile form. NET Intermediate Language (IL) Optical Code Node Code Single public base class is whether an exception handling exception handle returns an error exception handler. Learn about the important language features summarized in Table 1, please read it, learn about some important differences from C # and Java. Second, the comparison of language specification 2.1, simple data type Simple data type (Primitive) called value type in C #, C # predefined simple data types are more than Java. For example, C # has Unit, ie unsigned integers. Table 2 lists all C # predefined data types:
Table 2: Type Type Type of C # Description Object All Types of Final Pole String String Type; String is a Unicode Character Sequence Sbyte8 Belt Symbol Integer Short16 Bit Sign Integral INT32 Belt Symbol Integer Long64 Bit Symbol integer BYTE8 Non-symbol integers UIrt16 unsigned integer uint32-bit unsigned integer ulong64-bit unsigned integer float single-precision floating point type Double Double-precision floating point type Bool Boolean type; BOOL value or true, or falsechar character type; A Char value is a Unicode character decimal has a high-precision decimal type 2.2 of 28 valid numbers, and constants forget the Static Final modifier in Java. In C #, constants can be declared with a Const keyword.
Public const INT x = 55; In addition, the designer of C # also adds the Readonly keyword. If the compiler does not determine a constant value, you can use the Readonly keyword. The READONLY field can only be set by the constructor of the initializer or class. 2.3, the entry point of the public class in Java, the entry point of the public class is a common static method called Main. The parameter of the main method is a String object array, which does not return a value. In C #, the main method becomes a common static method main (uppercase M), the parameter of the main method is also an array of String object, and there is no return value, as shown in the following prototype, show: public static void main (String [String ] Args) However, the MAIN method of the C # is not limited thereto. If you do not pass any parameters to the main method, you can use an overload version of the above MAIN method, namely the version of the parameter list. That is, the following main method is also a legitimate entry point:
Public static void main () In addition, if you think it is necessary, the main method can also return an int. For example, the main method in the following code returns 1:
Using System; Public Class Hello {public static int main () {console.writeline ("done"); returnif 1;}} is relative, and the maintenance of the main load in Java is illegal. 2.4, Switch Statement In Java, the Switch statement can only handle an integer. However, the Switch statement in the C # is different, and it can also handle the character variable. Consider the C # code of the string variable with the Switch statement:
Using system; public class hello {public static void main (string [] args) {switch (args [0]) {case "boss": console.writeline ("Good morning! We are always ready for you!"); BREAK Case "Employee": console.writeline ("Good morning! You can start working!"); break; default: console.writeline ("Good morning! I wish you good luck!"); Break;}}} with Java Different from the Switch, the C # Switch statement requires each CASE block or a break statement at the end of the block, or goes with Goto to other Case tags in Switch. 2.5, Foreach Statement Foreach statement enumerates the individual elements in the collection, performs a code block for each element in the collection. See the example below.
Using system; public class hello {public static void main (string [] args) {foreach (string argin args) Console.writeline (arg);}} If the parameters are specified when running this execution file, such as "Hello Peter Kevin Richard ", the output of the program will be the following lines:
PeterkevinRichard 2.6, C # Nothing >>> Shift Operator C # supports unsigned variable types such as UINT and ULONG. Therefore, in C #, the right shift operator (ie, ">>") is different for unsigned variable types and symbolic variable types (such as int and long). Right shift UINT and ULONG discard the low and set the empty high position to zero; but for the INT and long type variables, ">>" operator discard the low position, while only when the variable value is positive, ">>" Set the empty high level to zero; if ">>" is a negative number, the high level of the empty out is set to 1. There is no symbolic variable type in Java. Therefore, we use the ">>>" operator to introduce the negative position at right time; otherwise, use the ">>" operator. 2.7, goto Keyword Java No goto keywords. In C #, GOTO allows you to go to the specified label. However, C # treats GOTO at a very cautious attitude, such as it does not allow GOTO to transfer to the inside of the statement block. In Java, you can add BREAK or Continue to replace C # in GOTO with a label statement. 2.8, the declaration array is very flexible in Java, and the array is very flexible, and there are many declaration methods that are legal methods. For example, the following lines of code are equivalent: int [] x = {0, 1, 2, 3}; int x [] = {0, 1, 2, 3}; but in C #, only the first If the line code is legal, [] cannot be placed behind the variable name. 2.9, package in C #, package (package) is called a namespace. The keywords who introduce the namespace into the C # program are "using". For example, "Using System;" This statement introduces the SYSTEM namespace. However, different from Java is that C # allows you to specify an alias for classes in the namespace or namespace:
Using theconsole = system.console; public class hello {public static void main () {Theconsole.writeline ("Using Alias");}} Although the Java's package class is similar to the namespace of .NET. However, the implementation of both is different. In Java, the name of the package is also an actual entity that actually exists, which determines the directory structure of the .java file. In C #, the name of the physical package and logic is completely separated, that is, the name of the namespace will not have any impact on the physical packaging method. In C #, each source code file can be from multiple namespaces, and it can accommodate multiple public categories. The entity in the .NET is called an assembly (ASSEMBLY). Each program set contains a Manifest structure. The Manifest lists the files contained in the assembly, control which types and resources are exposed to the assembly, and map the reference to these types and resources to files that contain these types and resources. The assembly is self-contained, and an assembly can be placed within a single file or split into multiple files. This package mechanism of .NET solves the problem facing the DLL file, that is, the inexperity DLL Hell problem. 2.10, the default package in Java, the java.lang package is the default package, which is automatically included without explicit imports. For example, you have to output some text to the console, you can use the following code:
System.out.Println ("Hello World from Java"); there is no default package in C #. If you want to output text to your console, you use the System Namespace Console object's WriteLine method. However, you must explicitly import all classes. The code is as follows: use system; public class hello {public static void main () {Console.Writeline ("Hello World from C #");}} 2.11, object-oriented Java and C # are all languages that are fully objects. In terms of three major principles for object-oriented programming, these two languages cannot be close.
Inheritance: Both languages support a single inherit of class, but the class can implement multiple interfaces. All classes are inherited from a public base class. Package and visibility: Whether in Java or C #, you can decide whether the class is visible. In addition to the C # INTERNAL access to the modifier, the visibility mechanism of the two is very similar. Polymorphism: Java and C # support certain forms of polymorphisms, and both implementations are very similar. 2.12, each member of the accessible class has specific types of accessibility. The access modifier in C # is a basic correspondence in Java, but there is more in Internal. In short, C # has five types of accessibility, as shown below:
PUBLIC: Members can access from any code. Protected: Members can only access from derived classes. INTERNAL: Members can only access internal access from the same assembly. Protected INTERNAL: Members can only access derived classes within the same program. Private: Members can only access within the current class. 2.13, derived class in Java, we use keyword "extends" to achieve inheritance. C # uses C class derived syntax. For example, the following code shows how to derive parent class Control to create a new class button:
Public class button: Control {.} 2.14, the final class Due to the final keyword in C #, if you want a class no longer being derived, you can use the Sealed keyword, as shown in the following example:
Sealed Class FinalClass {.} 2.15, interface interface This concept is very similar in C # and Java. The keywords for the interface are Interface, and an interface can extends one or more other interfaces. According to the practice, the name of the interface starts with uppercase letters "i". The following code is an example of a C # interface, which is exactly the same as the interface in Java:
Interface ishape {void Draw ();} The syntax of the extended interface is the same as the syntax of the extension class. For example, an IRECTANGULARSHAPE interface extends the ISHAPE interface (ie, the IRECTANGULARSHAPE interface is sent from the ISHAPE interface).
Interface IRECTANGULARSHAPE: ISHAPE {Int getWidth () If you derive from two or more interfaces, the name list of the parent interface is separated by commas, as shown in the following code:
Interface inewinterface: iParent1, iParent2 {} However, in different from Java, the interface in the C # cannot contain a domain (Field). Also note that in C #, all methods in the interface are common methods by default. In Java, the method declaration can carry a public modifier (even if it is not necessary), but in C #, the method explicitly specifies the PUBLIC modifier to be illegal. For example, the following C # interface will generate a compilation error. Interface ishape {public void Draw ();} 2.16, IS operator in the IS and AS Operation C # is the same as the InstanceOf operator in Java, both of which can be used to test whether an instance of an object belongs to a specific type. There is no operator in Java's AS operator equivalent to C #. The AS operator is very similar to the IS operator, but it is more "in-heart": If the type is correct, the AS operator will try to convert the object reference to the target type; otherwise, it sets the variable reference to null. To correctly understand the AS operator, first consider the use of the IS operator in this example. This example contains an ISHAPE interface and two class Rectangle and Circle that implements the ISHAPE interface.
using System; interface IShape {void draw ();} public class Rectangle: IShape {public void draw () {} public int GetWidth () {return 6;}} public class Circle: IShape {public void draw () {} public INT getRadius () {return 5;}} public class letsdraw {public static void main (string [] args) {ishape shape = null; if (args [0] == "Rectangle") {shape = new reccTangle (); } else if (args [0] == "circle") {Shape = new circle ();} if (Shape is rectangle) {Rectangle Rectangle = (Rectangle) Shape; console.writeline ("width:" Rectangle.Getwidth ());} IF (Shape IS CIRCLE) {Circle Circle = (Circle) Shape; Console.Writeline ("Radius:" Circle.GetRadius ());}}} After compiling the code, the user can enter "Rectangle" Or "circle" as a parameter of the main method. If the user enters "Circle", the Shape is instantiated into a Circle type object; in turn, if the user enters "Rectangle", the Shape is instantiated into an object of the Rectangle type. Subsequently, the program uses the IS operator to test the type of variable type: If Shape is a rectangle, the Shape is converted to the Rectangle object, we call its getWidth method; if Shape is a circle, Shape is converted into a Circle object, we Calling its GetRadius method. If the AS operator is used, the above code can be changed to the following form:
using System; interface IShape {void draw ();} public class Rectangle: IShape {public void draw () {} public int GetWidth () {return 6;}} public class Circle: IShape {public void draw () {} public INT getRadius () {return 5;}} public class letsdraw {public static void main (string [] args) {ishape shape = null; if (args [0] == "Rectangle") {shape = new reccTangle (); } else if (args [0] == "circle") {Shape = new circle ();} Rectangle Rectangle = Shape as Rectangle; if (Rectangle! = null) {Console.writeline ("Width:" Rectangle.GetWidth ());} else {circle circle = shape as circle; if (circle! = null) Console.Writeline ("Radius:" Circle.GetRadius ());}}} In the bold part of the above code, we In the case where the Shape object type is not tested, use the AS operator to convert the Shape into the object of the Rectangle type. If Shape is just a Rectangle, the Shape is converted into a rectangle type object and saves to Rectangle variables, then we call its getWidth method. If this conversion fails, we have a second attempt. This time, the Shape is converted into a Circle type object and saves the Circle variable. If Shape is indeed a Circle object, Circle now references a Circle object, we call its GetRadius method. 2.17, library C # has no own class library. However, C # shared the .NET class library. Of course, the .NET class library can also be used in other .NET language, such as VB.NET or JScript.net. It is worth mentioning that the StringBuilder class is a supplement to the String class. The StringBuilder class is very similar to the Java's StringBuffer class. 2.18, garbage collection C has made us realize how lack of efficiency and waste time. When you create an object in C , you have to remove this object. The more complicated the code, the more difficult this task is. Java uses a garbage collector to solve this problem, collecting the object that is no longer used by the garbage collector and releases memory. C # also uses this method. It should be said that if you are also developing a new OOP language, follow this road is a very natural choice. C # still retains the C memory manual management method, which is suitable for use in extremely important occasions, and this is not allowed in Java. 2.19, exception handling If you hear that C # uses an exception handling mechanism similar to Java, you won't be surprised, right? In C #, all exceptions are derived from a class named Exception (it is familiar?) In addition, as in Java, you have a familiar try and catch statements. The Exception class belongs to a part of the .NET System name.
Third, Java has no function C # Born after Java matures, therefore, C # has some Java (current) has not yet good features. 3.1 Enumerator Enumerator, ie ENUM type (Enumerator, or counter), it is a collection of related constants. Accurately, the Enum type declares a set of related symbol constants define a type name. For example, you can create an enumerator called FRUIT, use it as a type of variable value, thereby limiting the possible range of variables to the value that appears in the enumerator. PUBLIC CLAIT {Apple, Banana, Cherry, Durian} PUBLIC VOID Process (Fruit Fruit) {Switch (Fruit) {Case Fruit.Apple: ... Break; Case FRUIT.CHERRY: ... BREAK; CASE FRUIT.DURIAN: ... BREAK;}}} In the previous example, although you can use int as the type of MyVAR variable, but after using the enumerator fruit, The range of value of variables is limited to the value of Applet, Banana, Cherry and Durian. Compared with INT, Enum readability is better, and self-explanatory ability. 3.2, structural structure (Struct) is very similar to the class. However, the class is created as a reference type in the heap, and the structure is a value type, which is stored in the stack or embedded. Therefore, as long as it is careful, the structure is faster. The structure can implement an interface, which can be as a class, but the structure does not support inheritance. However, simply use the structure to replace the class may result in heavy losses. This is because the structure is transmitted in a value. Since this transmission method is to be copied to a new location, it is necessary to overhead to the "obese" structure. For classes, simply deliver it when passing. Here is an example of a structure. Note that it is very similar to the class, just replace the word "struct" to "Class", you get a class.
Struct Point {public Int x, y; public point (int x, int y) {this.x = x; this.y = y;}} 3.3, attribute C # classes In addition to the field, it also You can have properties. Attribute is a characteristic of named class or object. Attributes are a natural extension of the domain - both have types, and a name-based class member. However, the domain is different, the attribute does not represent a storage location; in contrast, the property has an Accessor, the accessor defines the code that must be performed when reading or writing attribute values. Therefore, the attribute provides a mechanism that associates the operation and reading of the object value value, and they allow attribute values to be calculated. In C #, the properties are defined by the attribute declaration syntax. The first part of the attribute declaration syntax is similar to the domain statement, and the second portion includes a set procedure and / or a GET process. For example, in the example below, the PropertyDemo class defines a PROP attribute.
Public class protydemo {private string prop;} set {prop = value;}}}} If the property is allowed to write allow written, such as the PropertyDemo class's Prop property, it also has GET And the SET access process. When we read the value of the attribute, the GET access process is called; when we write attribute values, the SET access process is called. During the SET access, the new value of the property is given in a hidden value parameter. Like a method of reading and writing an domain, attributes can also be read and written in the same syntax. For example, the following code instantiates a PropertyDemo class and then writes to read its PROP properties. PropertyDemo Pd = New PropertyDemo (); pd.prop = "123"; // setString s = pd.prop; // GET 3.4, delivering a simple data type in Java in Java in Java, using a simple data type When the value is passed to the method as a parameter, the parameter is always transmitted in a value - ie, the system will create a copy of the parameter value to the called method. In C #, you can pass a simple data type with reference to the value of a simple data type. At this point, the called method will directly use the value passed to it - that is, if the value of the parameter is modified inside the called method, the original variable value also changes. When the value is transmitted in the c #, we use the REF keyword. For example, if you compile and run the following code, you will see the output results 16 on the console. Note how the I value is passed to ProcessNumber.
Using system; public class passbyreference {public static void main (string [] args) {INT i = 8; ProcessNumber (Ref i); console.writeline (i);} public static void processnumber (Ref int J) {j = 16 There is also a keyword OUT that allows parameters to deliver parameters in a reference method, which is similar to REF. However, when using OUT, the variables transmitted as parameters do not have to have known values until passed. In the above example, if the integer i is not initialized before passing to the ProcessNumber method, the code will be wrong. If you replace REF with OUT, you can pass an uninitial value, as shown in this modified example.
Using system; public class passbyreference {public static void main (string [] args) {INT i; processnumber (out i); console.writeline (i);} public static void processnumber (Out Int I) {j = 16;} } After the modification, although the I value is not initialized before passing to the ProcessNumber method, the PassbyReference class can smoothly pass compilation. 3.5, C # retains the new developers who feel that they can just use their pointers and be happy to manually perform memory management, they can still use the "old" pointer that is neither safe and not easy to use. The performance of the program. C # provides the ability to support "unsafe" code, which can direct the pointer directly to "fix" objects to temporarily block the garbage collector from moving objects. Regardless of the developer or the user's vision, this support for "unsafe" code is actually a security function. The "unsafe" code must be explicitly indicated with UNSAFE keywords, so developers cannot use "unsafe" code in unintentional. At the same time, the C # compiler is collaborated with the execution engine to ensure that the "unsafe" code cannot be disguised to become a security code. UnsAFE code in (byte [] arr) {.}}}}}}} C # in the following case: When the speed is extremely important, or when the object needs to be with existing software (for example C-code in the COM object or DLL form) interacts. 3.6, agent agent (DELEGATE) can be seen as a function pointer in C or other languages. However, different from the function pointer is that the agent in the C # is an object-oriented, type safe, reliable. Moreover, the function pointer can only be used to reference the static function, but the agent can reference the static method and can reference the instance method. Agent is used to encapsulate the calling method. You can write a method in the class and create a proxy on that method, and this agent can be passed to the second method. In this way, the second method can call the first method. The agent is a reference type derived from the public base class system.delegate. Definitions and Use Agents include three steps: declaration, create an instance, call. The agent declaration with Delegate declaration grammar. For example, a proxy that does not require parameters and does not return value can be declared by code: