C # is built on C + + syntax and semantics, allowing programmers to use C language. NET common language runtime and the convenience brought. Despite the shift from C + + C # is relatively easy, but some areas still deserve our attention.
This article will focus shifted from the C + + C # when the biggest changes: the non-managed environment to changes in the environment can be managed. Additionally, some C # programmers easy to mistake for your reference, and will describe some of the C # programming language to influence the new features.
Shift to the management of the environment
C + + design goal is low-level, platform-independent object-oriented programming language, C # is an advanced component-oriented programming language. Changes in the regulatory environment can mean that you think the major changes programmatically, C # is no longer dealing with fine control, but to give structure to help you address these important issues. For example, in C + +, we can use the new in the stack, heap, or even a specific location in memory to create an object.
In. NET-managed environment, we need not be as fine control. In selected to create the type, its location is fixed up. Simple types (ints, double and long) of the object is always created on the stack (unless they are included in other objects), classes are always created in the heap. We can not control what the object is to create a position in the heap, there is no way to get this address, the object can not be placed in a specific location in memory. (Of course, there are ways to break through these limits, but is an alternative method.) We can no longer control the object's life cycle, C # no destructor. Debris collection program will object to recall the memory, but the non-dominant manner.
This structure is the C # reflection of its infrastructure, which is not multiple inheritance and templates, because in a managed environment of debris collection, multiple inheritance is difficult to efficiently achieve.
C # in a simple type is the only common language runtime (CLR) in the type of simple mapping, for example, C # The int is System.Int32 mapping. C # in the data type is not determined by the language itself, but the decision by the CLR. In fact, if still want to use in C #, VisualBasic object created, they must make their programming habits more in line with the provisions of CLR.
On the other hand, can manage the environment and the CLR have also brought benefits to us. In addition to debris collection and all. NET languages in a unified data types, it also provided us with a powerful component-oriented programming language, Wu Xu binding on the latter to provide special support Leixingfaxian and late binding Dushi was built in the language. Attribute is C # language in the first category of membership, events, and agents also.
May be the most important advantage is that management of the environment. NETFramework. Despite all of the. NET languages can use this framework, but C # can make better use of. NET Framework rich classes, interfaces and objects.
Traps
C # and C + + looks very similar, which makes us turn from the C + + C # relatively easy time, but there are some trouble spots. Written in C + +, very nice code in the C # compiler will not pass, even unexpected results. C # and C + + between the change in the grammar is not great, the compiler can find most of the difference between these two, I am not any further words here, and here I introduce a few more error-prone important changes:
Reference types and value types
In C #, value types and reference types of data are different. Simple types (int, long, double, etc.) and structural data are value types, classes and objects are reference types of data. Unless it is included in a reference type variable, and in C + +, the same value type variables are stored in the stack. Reference type variable is also stored in the stack, but its value is stored in the address of the object heap, which is also similar with C + +. Value type variable is passed to the method of their value, while the reference pointer type variable will be passed to the method of their own.
Structure
C # in the structure and C + + in a very clear distinction. In C + +, the structure is more like a class, in addition to the default inheritance, the access of its default is public and not private. In C #, structure and distinct class, which is used to package and light objects, is a value type of data type, when the transmission is in the transfer value of the variable, rather than its address. In addition, they also have some type of restriction does not apply, for example, it can not be inherited, and no addition to the basic category than System.ValueType. Structure can not define a default constructor.
On the other hand, due to the efficiency of the structure is higher than the class, so it is very suitable to create a light object. Therefore, if it's shortcomings do not affect your software, use the structure than using the class is much higher, especially for small objects is concerned.
Everything is an object
In C #, all things are received by the inherited Object, including the creation of the class and int, structs equivalent type of variable. Object class provides some useful methods such as ToString, use the ToString example is used in conjunction with System.Console.WriteLine, it can accept a string and a number of objects. Printf statement with the use of different, to use the WriteLine, the need for substitution variables. Suppose myEmployee is a user-defined an instance of Employee class, myCounter user-defined Counter is an instance of the class:
Console.WriteLine ("Theemployee: (0), thecountervalue: (1)",
myEmployee, myCounter);
Which calls the WriteLine method of each object Object.ToString, replace the variable as a parameter to return. If the Employee class does not override ToString, will call the default implementation (inherited from the System.Object obtained), it will put the class name as a string to return. Counter override ToString, returns an integer variable, so the output of the code above:
Theemployee: Employee, thecountervalue: 12
If an integer variable passed to the WriteLine What happens then? Since integer variables can not call ToString, the compiler will automatically be integer variables encapsulated in an object instance. When the WriteLine call to ToString, the object will return the string value of that integer variable. The following code illustrates this problem:
The use of class
usingSystem;
/ / Do not override ToString in class
publicclassEmployee
(
)
/ / Cover class ToString
publicclassCounter
(
privateinttheVal;
publicCounter (inttheVal)
(
this.theVal = theVal;
)
publicoverridestringToString ()
(
Console.WriteLine ("CallingCounter.ToString ()");
returntheVal.ToString ();
)
)
publicclassTester
(
publicstaticvoidMain ()
(
/ / Create an instance of class
Testert = newTester ();
/ / Call non-static members
/ / (Mustbethroughaninstance)
t.Run ();
)
/ / Demonstrate the non-static method called ToString
publicvoidRun ()
(
EmployeemyEmployee = newEmployee ();
CountermyCounter = newCounter (12);
Console.WriteLine ("Theemployee: (0), thecountervalue: (1)",
myEmployee, myCounter);
intmyInt = 5;
Console.WriteLine ("Herearetwointegers: (0) and (1)", 17, myInt);
)
)
Reference parameters and output parameters of
The same with C + +, C # the method can only return a value. In C + +, we passed the pointer or index as a parameter to overcome this restriction, which is called the method of changing the parameters, call the method can get the new value of.
Pass an index to the method as a parameter, the only strictly by passing the index or pointer can provide access to the original object. For the value type variable is concerned, we can not use the method. If you want to pass by reference type parameter value type variable, you need to add in front of ref Key words. As follows:
publicvoidGetStats (refintage, refintID, refintyearsServed)
Note that both methods require the use of the definition of ref Key words, but also the practical need to call in the way Key words used in ref.
Fred.GetStats (refage, refID, refyearsServed);
Now, we can call the method defined in the age, ID and yearsServed variables, pass them to the GetStats, get the changed value.
C # requires a clear assignment, that is, before calling GetStats method, must be age, ID and yearsServed three local variable is initialized, this work seems a bit redundant, because we only use them to get new from GetStats variable value. To solve this problem, C # provides a key word out that we can pass to the method is not initialized variables, these variables will be conducted through the reference variable transmission:
publicvoidGetStats (outintage, outintID, outintyearsServed)
Of course, calling the method must also make corresponding changes:
Fred.GetStats (outage, outID, outyearsServed);
New call
In C + +,, new Key words can generate an object on the heap. In C #, is not the case. The terms of reference type variables, new key word generate an object on the heap; types of variables in terms of structural equivalence, new key word to generate an object on the stack, and need to call the constructor.
In fact, we can not use the new key word in the stack to generate a structure type of variable, but this time to note that, New Key words to initialize the object. If you do not use new, you must manually before use of the structure to initialize all members, or at compile time error.
Object initialization
usingSystem; / / There are two member variables and a simple structure constructor
publicstructPoint
(
publicPoint (intx, inty)
(
this.x = x;
this.y = y;
)
publicintx;
publicinty;
)
publicclassTester
(
publicstaticvoidMain ()
(
Testert = newTester ();
t.Run ();
)
publicvoidRun ()
(
Pointp1 = newPoint (5,12);
SomeMethod (p1); / / fine
Pointp2; / / do not call directly to create new
/ / Compiler error here will, as a member variable p2 is not initialized
/ / SomeMethod (p2);
/ / Manually initialize them
p2.x = 1;
p2.y = 2;
SomeMethod (p2);
)
/ / Point as a parameter to an acceptable method of
privatevoidSomeMethod (Pointp)
(
Console.WriteLine ("Pointat (0) x (1)",
p.x, p.y);
)
)
Property
Most of the C + + programmers hope to make a member variable of the property is private, 杩欑 hidden data in the idea of Cujin the data packaging concept of the Chuxian, so 鎴戜滑 can not change the users rely on the interface, but to, the realization of the changed. Normally, we only want our customers to get or set the member variable values. Therefore, C + + programmers developed to access the private member variable of the access device.
In C #, attributes are first-class members of the class. For customers, the property looks like a member variable. For those who like to achieve, the way it looks more like. This design is clever, both hidden and packaging of data, but also allows customers to easily access member variables.
We can add an Age Employee class attribute, so that customers can easily access and set the age of the staff members of the class:
publicintAge
(
get
(
returnage;
)
set
(
age = value;
)
)
Key words hidden attribute value can be use. If you write the following code:
Fred.Age = 17;
Compiler will pass the value 17 value.
Instead of by using only Get Set, we can create a read-only attribute YearsServed:
publicintYearsServed
(
get
(
returnyearsServed;
)
Use) Accessors
privatevoidRun ()
(
EmployeeFred = newEmployee (25,101,7);
Console.WriteLine ("Fred''sage: (0)",
Fred.Age);
Fred.Age = 55;
Console.WriteLine ("Fred''sage: (0)",
Fred.Age);
Console.WriteLine ("Fred''sservice: (0)",
Fred.YearsServed);
/ / Fred.YearsServed = 12; / / is not allowed
)
We can get Fred property age, you can also use this property to set the age. While we can get it to access YearsServed property value, but can not set the value. If you do not comment out the last line of code, at compile time error occurs.
If you later decide to obtain from the database Employee's age, we only need to change the access to the system implementation, the client will not be affected.
相关链接:
Compare Browser ToolsPs3 Movie FormatsCommand & Conquer 3 - the most difficult opponents experiencefree mov to wmv converterEASY News ServersWave of mergers BI have a happy lifeIn October 2007 the Sixth New York International Outsourcing ExhibitionUlead SmartSaver Pro 3.0 Cheats bit through (c)Win 7 random and Changed anti-piracy measures become soft blackMpeg4 To Mp4Was brilliant: Ten-man Weapon crack revealed inside story of classicalC # in the Delegate and eventOptional Memory Must Answer Three QuestionsIn SDH / SONET 155M On Carrying IP Packet SolutionEasy to use Communications Toolsm4a to mp3 converter