We know, C # and C + + syntax is very similar, from a C + + to C # transformation, the difficulty is not the language itself, but rather familiar. NET-managed environment and on. NET framework for understanding.
Although C # and C + + in grammatical change is very small, almost not have any impact, but some changes are enough to make some careless moment of C + + programmers in mind. In this article we will discuss the C + + programmers the ten most likely to commit errors.
Trap 1: there is no clear end of the method
Almost completely sure that, for most in terms of C + + programmers, C # and C + + the biggest difference is that debris collection. This also means that programmers no longer need to worry about memory leaks and make sure to remove all the useless pointer. But we can no longer accurately control the process kill useless objects. In fact, in C #, there is no clear destructor.
If the use of non-management resources, without the use of these resources, you must explicitly release it. Recessive control of resources by Finalize method (also known as the finalizer) provided, when the object is destroyed, it will be called to recover debris collection program resources occupied by the object.
finalizer should only release the destruction of the object occupied Non-management resources, and other objects should not be involved. If the program is only used to manage resources, it need not be the implementation of Finalize method, only the non-manageability of resources will be used in the treatment of Finalize method. As the need to take up certain resources finalizer, it should only need it to perform the method finalizer.
Directly call an object's Finalize method is not permitted (except in sub-class called base class Finalize Finalize.), Debris collection program will automatically call Finalize.
From the syntax point of view, C # in the destructor and C + + is very similar, but in fact they are completely different. C # the destructor definition of Finalize method is a shortcut. Therefore, the following Erduan code is different:
~ MyClass ()
(
/ / Need to complete the task
)
MyClass.Finalize ()
(
/ / Need to complete the task
base.Finalize ();
)
Error 2: Finalize and Dispose to use whom?
From the above discussion, we have been very clear, explicit to call the finalizer is not allowed, it can only be called debris collection program. If you want to free up some no longer in use as soon as possible a limited number of non-managed resources (such as file handles), you should use the IDisposable interface, the interface has a Dispose method, which can help you accomplish this task. Dispose is no need to wait for Finalize to be called and be able to release the non-manageability of resources.
If you have used the Dispose method, you should stop the debris collection process and then the corresponding object method implementation of Finalize. To do this, you need to call the static method GC.SuppressFinalize, and the corresponding object pointer passed to it as a parameter, Finalize method can call the Dispose methods. Accordingly, we can get the following code:
public void Dispose ()
(
/ / Complete clean-up operation
/ / Notify the GC not to call Finalize method
GC.SuppressFinalize (this);
)
public override void Finalize ()
(
Dispose ();
base.Finalize ();
)
For some objects, may call the Close method is more suitable (for example, the document object calls Close on more appropriate than Dispose), you can create a private property of the Dispose method and the Close method of public property, and to call Dispose to realize Close call the Close method of some object.
Given the uncertainty will call Dispose, but the implementation is uncertain finalizer (we can not control when the GC will run), C # provides a Using statement to ensure the Dispose method will be called the earliest possible time. General approach is to define which objects to use, then use brackets for these objects to specify a range of activities, in the event when the innermost parentheses, Dispose method will be automatically invoked, the object for processing.
using System.Drawing;
class Tester
(
public static void Main ()
(
using (Font theFont = new Font ("Arial", 10.0f))
(
/ / Use theFont object
) / / Compiler will call Dispose object processing theFont
Font anotherFont = new Font ("Courier", 12.0f);
using (anotherFont)
(
/ / Use anotherFont object
) / / Compiler will call Dispose object processing anotherFont
)
)
In this case, the first part, Font object is created in the Using statement. When the Using statement at the end, the system will call Dispose, on the Font object for processing. In this case, the second part, Font object is created in the Using statement outside, in the decision to use it, then place it inside the Using statement, when the Using statement at the end, the system will call Dispose.
Using statement can also prevent other accidents from occurring, ensure that the system will call Dispose.
Error 3: C # in the value-type variables and reference-type variables are different
As with C + +, C # is a strongly typed programming language. C #, data types are divided into two categories: C # language itself, the inherent data types and user-defined data types, which is also similar with C + +.
In addition, C # language Hai Ba variables are divided into value types and reference types. Unless it is to be included in a reference type, value type variables retained in the stack, this point and C + +, variables are very similar. Reference type variable is a stack, its value is the address of the object heap, and C + +, the pointer is very similar. Value type variable value is directly passed to the method of reference-type variables are passed as parameters to the method, passing the index.
Classes and interfaces can create reference type variable, but need to point out that structure data type is a built-in C # data types, it is also a value-based data types.
Error 4: Note that implicit data type conversion
Boxing and unboxing enable value data type is used as the index data type using the two processes. Value-type variables can be packaged into an object, and then the return value is unpacked variables. Including built-in data types, including C #, the data of all types can be implicitly converted to an object. Packing a value type variable will generate an object instance, and then copied to the instance variable.
Boxing is implicit, if necessary where the index data type data type using a value type variable, the value of hidden variable will be transformed into the index data type of variable. Boxing will affect the performance of code execution, so should be avoided, especially when the data volume.
If you want to convert a packed object back to the original value type variable, it must be explicit to be unpacked. Unpacking need two steps: First, the object instance checks to ensure they are shaped by the values of variables are packaged into the; second step in the value of the instance to copy the value type variable. In order to ensure a successful solution package was unpacked the object must be packing a value type variable by the value of the index generated objects.
using System;
public class UnboxingTest
(
public static void Main ()
(
int i = 123;
/ / Package
object o = i;
/ / Solution Package (must be the dominant)
int j = (int) o;
Console.WriteLine ("j: (0)", j);
)
)
If the object is unpacked is not valid, or a different data type object index will result InvalidCastException different things.
Error 5: Structure and objects are different
C + + structures and classes in the almost, the only difference is that by default, the structure of access is public, its inheritance rights is public. Some C + + programmers to structure as a data object, but this is not a convention must be the case.
In C #, the structure is only a user-defined data types, and can not be substituted. Although the structure of the support properties, methods, fields and operators, but does not support inheritance and destructor.
More importantly, the class is an indexed data type, the structure is a value type data type. Therefore, the structure of the index operation in the expression of the target area without more useful. Array of operational structure more efficient, and in the operational aspects of the collection is less efficient. Set to index, structure must be packaged is suitable for use in the operation of the collection, a collection of classes in the large-scale operations more efficient.
Error 6: Virtual methods must be explicitly covered
In the C # language, the programmer of a virtual method in the coverage must be the dominant use of the override key word. Suppose a Window class is written by the A company, ListBox and RadioButton classes by B's and programmers in the company prepared to buy the A Window on the basis of class, prepared, B Company of the programmers of the Window class, including changes in the future little is known about the situation, including the design.
If the B's, a programmer to add a ListBox Sort method:
public class ListBox: Window
(
public virtual void Sort () (")
)
A company release a new version in the Window class before, this will not have any problems. A company if the Window class programmers also added a Sort method.
public class Window
(
/ / "
public virtual void Sort () (")
)
In C + +,, Windows class will be the ListBox Sort method Sort method of the class based approach, in the hope of calling Windows class Sort method, ListBox class Sort method will be invoked. In C #, virtual function is always considered to be the root of virtual dispatch. In other words, once C # finds a virtual method, you will not find in the virtual chain other virtual methods. If the ListBox is compiled again, the compiler will generate a warning message:
"Class1.cs (54,24): warning CS0114:''ListBox.Sort ()''hides
inherited member''Window.Sort ()''.
For the current members of the original method of coverage, you need to add the override key word, or add new key word.
To remove the warning message, the programmer must find out what he wants. ListBox class can be added before the Sort method new, that it should not override the virtual method in Window:
public class ListBox: Window
(
public new virtual void Sort () (")
This could clear the warning. If the programmer really want to overwrite methods in the Window, you must use the override key word to demonstrate its intentions explicit.
Error 7: class member variable initialization
C #, C + + initialization and different. Suppose there is a character with a private member variable age of the Person class, Employee class is generated by a succession of Person, and it has a private member variable nature of salaryLevel. In C + +, we can initialize the Employee's constructor initializes some salaryLevel, as shown in the following code:
Employee:: Employee (int theAge, int theSalaryLevel):
Person (theAge) / / initialize base class
salaryLevel (theSalaryLevel) / / initialize member variable
(
/ / Constructor code
)
This method in C #, is illegal. While still can initialize base class, but as the code above as initializes the member variable will cause a compiler error. In C #, we can define a member variable to initialize it when the same:
Class Employee: public Person
(
/ / Member variable definition
private salaryLevel = 3; / / initialization
)
Note: You must explicitly define each variable access.
Error 8: Boolean variables and integer variables are different from children
if (someFuncWhichReturnsAValue ())
In C #, Boolean variables and integer variables are not the same, so the following code is incorrect:
if (someFuncWhichReturnsAValue ())
if someFuncWhichReturnsAValue return to zero, said false, or that the idea is no longer true. The advantage is that the original assignment operator there will be confused with the same error will not happen again. So the following code:
if (x = 5)
At compile time error occurs because the x = 5 is the 5 assigned to the X, rather than a Boolean value.
Error 9: switch statements would be less than the implementation of some statement
In C #, if a switch statement to implement a number of operations, the program may not perform to the next statement. Thus, while the following code in C + + is legal, but in C #, not legal:
switch (i)
(
case 4:
CallFuncOne ();
case 5: / / error, will not be executed here
CallSomeFunc ();
)
To achieve the above purpose of the code needed to use a goto statement:
switch (i)
(
case 4:
CallFuncOne ();
goto case 5;
case 5:
CallSomeFunc ();
)
If the case statement does not execute any code, all the statements will be executed. Such as the following code:
switch (i)
(
case 4: / / can perform to
case 5: / / can perform to
case 6:
CallSomeFunc ();
)
Error 10: C # in the clear assignment of variables required
In C #, all the variables must be assigned before use. Therefore, you can define variables not initialize it, if it is passed to a method before, must be assigned.
If the only way through the index to pass a variable, and the variable is the method of output variables, this is it will cause problems. For example, suppose there is a method that returns the current time, hour, minute, second, if the write code like this:
int theHour;
int theMinute;
int theSecond;
timeObject.GetTime (ref theHour, ref theMinute, ref theSecond)
If you use theHour, theMinute and theSecond not before the three variables are initialized, it will generate a compiler error:
Use of unassigned local variable''theHour''
Use of unassigned local variable''theMinute''
Use of unassigned local variable''theSecond''
We can initialize these variables to 0 or other methods did not affect the value of the return value to solve this small problem the compiler:
int theHour = 0;
int theMinute = 0;
int theSecond = 0;
timeObject.GetTime (ref theHour, ref theMinute, ref theSecond)
This little too cumbersome, these variables are passed to the GetTime method, then change it. To solve this problem, C # specifically for this situation out parameter modifier provided, it can make an argument without initialization can be cited. For example, GetTime parameters in its own makes no sense, they are just to express the output of the method. Before the method returns, Out parameters must be assigned a value. Here is the revised GetTime methods:
public void GetTime (out int h, out int m, out int s)
(
h = Hour;
m = Minute;
s = Second;
)
Here is a new method called GetTime method:
timeObject.GetTime (out theHour, out theMinute, out theSecond);
Recommended links:
China IPTV-What is the short board?Experts Return Weapon entertainment, travel to save moneySpecialist Games ArcadeEasy E-MAIL ClientsLearning regular expressions entirely Manual: Getting Started guide rookieB2C Mall To Promote The Six-pulse SwordAvchd to xbox 360Deep Antivirus Guide (3)Mars V2.7.2 latest version of the text input text input easy FunRemain a top: the blue SEA toNine ways to recruit good StaffThe more competition the more powerful SymantecFlv to mp3 converter free downloadmov to aviMp3 to 3g2