Changes from C ++ to C # Notes (2)

Source: Internet
Author: User

Introduction: every 10 years or so, programmers need to spend a lot of time and energy learning new programming technologies. In 1980s, it was Unix and C, and in 1990s it was Windows and C ++. Now it has reached Microsoft's. NETFramework and C #. Although new technologies need to be learned, the benefits are far higher than the labor cost. Fortunately, the analysis and design of most projects using C # And. NET have no essential changes in C ++ and Windows. In this article, I will introduce how to make a leap from C ++ to C.

Series of articles: [switching from C ++ to C # changes that need attention (1)]

New call

In C ++, the new parameter can generate an object on the heap. This is not the case in C. For reference type variables, the new Guan Jian word generates an object on the heap. For structure equivalent type variables, the new Guan Jian word generates an object in the stack and needs to call constructor.

In fact, we can generate a structure type variable on the stack without using the new Guan Jian character, but note that the New Guan Jian word can initialize the object. If new is not used, all members in the structure must be initialized manually before use. Otherwise, an error occurs during compilation.

Object initialization


UsingSystem; // has two member variables and a simple structure of the 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; // create directly without calling new

// An error occurs when the compiler compiles it here because the p2 member variable is not initialized.
// SomeMethod (p2 );

// Initialize them manually
P2.x = 1;
P2.y = 2;

SomeMethod (p2 );

}
// A method that accepts a Point as a parameter
PrivatevoidSomeMethod (Pointp)
{
Console. WriteLine ("Pointat {0} x {1 }",
P. x, p. y );
}
}


Attribute

Most C ++ programmers want to make member variables private. This idea of hiding data promotes the emergence of the concept of data encapsulation, this allows us to change the implementation of classes without changing the interfaces on which users depend. In general, we only want the customer to get or set the values of these member variables. Therefore, C ++ programmers have developed an accesser to access private member variables.

In C #, an attribute is the first member of a class. For customers, attributes look like a member variable. For the implementer of the class, it looks more like a method. This design is clever. It not only hides and encapsulates data, but also enables users to conveniently access member variables.

We can add an Age attribute to the Employee class so that the customer can easily obtain and set the members of the Employee Age class:


PublicintAge
{
Get
{
Returnage;
}
Set
{
Age = value;
}
}


The parameter value can be implicitly used by attributes. If you write the following code:


Fred. Age = 17;


The compiler will pass the value 17 to the value.

By using Get instead of Set, we can create a read-only attribute for YearsServed:


PublicintYearsServed
{
Get
{
ReturnyearsServed;
}
} Accessors usage
PrivatevoidRun ()
{
EmployeeFred = newEmployee (25,101, 7 );
Console. WriteLine ("Fredsage: {0 }",
Fred. Age );
Fred. Age = 55;
Console. WriteLine ("Fredsage: {0 }",
Fred. Age );


Console. WriteLine ("Fredsservice: {0 }",
Fred. YearsServed );
// Fred. YearsServed = 12; // it is not allowed
}
 


We can get the Fred's age through the property, or use this property to set the age. Although we can access the YearsServed attribute to obtain its value, we cannot set the value. If the last line of code is not commented out, an error occurs during compilation.

If we decide to get the age of the Employee from the database in the future, we only need to change the implementation of the accesser, and the customer will not be affected.

Array
C # provides an array class, which is more intelligent than traditional arrays in C/C ++. For example, writing an array in C # does not exceed the boundary. In addition, the array has a more intelligent partner-ArrayList, which can dynamically increase and manage the changing array size requirements.

Arrays in C # Have three forms: one-dimensional arrays, multi-dimensional even arrays (like traditional arrays in C ++), and non-even arrays (arrays ). We can use the following code to create a one-dimensional array:


Int [] myIntArray = newint [5];
In addition, you can initialize it as follows:

Int [] myIntArray = {2, 4, 6, 8, 10 };

We can create a 4 × 3 even array as follows:

Int [,] myRectangularArray = newint [rows, columns];

We can initialize the array as follows:

Int [,] myRectangularArray =
{
{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {9, 10, 11}
};
 

  

Since an uneven array is an array, we can only create a one-dimensional non-uniform array:


Int [] [] myJaggedArray = newint [4] [];

Then create each internal array:


Myjagedarray [0] = newint [5];
Myjagedarray [1] = newint [2];
Myjagedarray [2] = newint [3];
Myjagedarray [3] = newint [5];


Because arrays are obtained by Inheriting System. Array objects, they carry many useful methods including Sort and Reverse.

Indexer

We can create objects like arrays. For example, we can create a list box that displays a series of strings and treat the list box as an array. Using an index, we can easily access the content in the list box.


StringtheFirstString = myListBox [0];
StringtheLastString = myListBox [Length-1];


This is done through the indexer. The indexer is very similar to an attribute, but supports the syntax of index operations. Figure 4 shows an attribute followed by the index operator. Figure 5 shows how to complete a simple ListBox class and index it:

Interface

The software interface is a contract for interaction between two objects. If an object publishes an interface, it is declared to all possible customers: I support the following methods, attributes, events, and indexers.

C # is an object-oriented language. Therefore, these contracts are encapsulated in an object called an interface. The interface defines the referenced objects that encapsulate the contract. In terms of concept, the interface is very similar to the abstract class. The difference between the two is that the abstract class can be used as a basic class of a series of classes, and the interface is combined with other inheritance trees.



 

 


 

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.