> Fourth C # type (Rainbow translation) (from heavy particle space)

Source: Internet
Author: User
Tags abstract define exception handling expression numeric value variables first row variable
<< Show c#>> Fourth Chapter C # type (Rainbow translation)


Source: http://www.informit.com\matter\ser0000002\chapter4\ch04_04.shtml

Body:

Fourth C # types

Now that you know how to create a simple C # program, I'll introduce you to C # 's type system. In this chapter, you learn how to use different values and reference types, what the box and frame mechanism can do for you. Although this chapter does not focus on examples, you can learn a lot of important information about how to create ready-made types of programs.
4.1 Value types
The various value types always contain a value of the corresponding type.     C # forces you to initialize variables to use them for calculation-variables that are not initialized will not cause problems because when you attempt to use them, the compiler will tell you. Whenever a value is assigned to a value type, the value is actually copied. In contrast, for reference types, only the reference is copied, and the actual value remains in the same memory location, but now two objects are pointing to it (referencing it). The value types of C # can be categorized as follows:
• Simple Type (plain types)
• Structure type (struct types)
• Enumeration type (enumeration types)
4.1.1 Simple Type
Simple types that appear in C # share some attributes. First, they are all. NET system type alias. Second, a constant expression consisting of simple types is detected only at compile time and not at runtime. Finally, simple types can be initialized literally. The following is a C # Simple type collation:
• Integral type
• Boolean type
· Character type (a special case of an integral type)
• Floating-point type
• Decimal Type

4.1.1.1 Integral type
There are 9 integral types in C #. SByte, Byte, short, ushort, int, uint, long, ulong, and char (discussed in a separate section). They have the following characteristics:

The sbyte type is a signed 8-bit integer with a value range between 128~127.
The bytet type is an unsigned 16-bit integer with a value range between 0~255.
The short type is a signed 16-bit integer with a value range between -32,768~32,767.
The ushort type is an unsigned 16-bit integer with a value range between 0~65,535.
The int type is a signed 32-bit integer with a value range between -2,147,483,648~ 2,147,483,647.
The uint type is an unsigned 32-bit integer with a value range between 0 ~ 4,294,967,295.
The long type is a 64-bit signed integer with a value range between 9,223,372,036,854,775,808~ 9,223,372,036,854,775,807.
The ulong type is a 64-bit unsigned integer with a value range between 0 ~ 18,446,744,073,709,551,615.

Both VB and C programmers may be surprised by the new range represented by the int and long data types. In C #, the int no longer depends on the size of the word (word) of a machine, and long is set to 64 bits, compared to other programming languages.

4.1.1.2 Boolean type
The Boolean data type has True and false two Boolean values. You can assign a value of TRUE or False to a Boolean variable, or you can assign an expression that evaluates to one of two:
BOOL Btest = (> 90);
In C #, the true value is no longer any value other than C and C + +. Do not convert other integral types to Boolean for added convenience.

4.1.1.3 Character type
The character type is a single Unicode character. A Unicode character is 16 bits long and can be used to represent multiple languages in the world. You can assign a value to a character variable in the following ways:
Char Chsomechar = ' A ';
In addition, you can assign a value to a variable (prefix \u) by using a hexadecimal escape character (prefix \x) or Unicode notation:
Char Chsomechar = ' \x0065 ';
Char Chsomechar = ' \u0065 ';
There is no implicit conversion that converts char to another data type. This means that it is not feasible to treat a character variable as another integer data type in C #-This is another aspect of C programmers ' need to change their habits. However, you can use explicit conversions:
Char Chsomechar = (char) 65;
int nsomeint = (int) ' A ';
The escape character (character meaning) still exists in C. To change give our minds, please see table 4.1.

Table 4.1 escape character (escape sequences)

Escape character Name
\ ' Single quotes
\ "Double Quotes
\ reverse Slash
Null characters
\a exclamation point (Alert)
\b Backspace
\f Page Change
\ n New Line
\ r Carriage Return
\ t Horizontal tab
\v Vertical Tab

4.1.1.4 floating-point type
Two types of data are treated as floating-point: float and double. They differ in value range and precision:
Float: The range of values is between 1.5x10^-45~ 3.4x10^38, with a precision of 7 digits.
Double: The range of values is between 5.0x10^-324 ~ 1.7x10^308, and the precision is 15~16 digits.
When you perform an operation with two floating-point types, you can produce the following values:
Positive zero and minus 0
Positive infinity and negative infinity
Non-numeric value (Not-a-number, abbreviated Nan)
A finite number set of non-0 values
Another rule is that when one value in an expression is a floating-point type, all other types are converted to floating-point type to perform the operation.

4.1.1.5 decimal type (the decimal type)
A decimal type is a high-precision, 128-bit data type that is intended for financial and monetary calculations. It represents a range from approximately 1.0x10^-28 to 7.9x10^28, with 28 to 29 digits of valid digits. Note that the precision is expressed in bits (digits) rather than decimal digits (places). The operation is accurate to a maximum of 28 decimal places.
As you can see, it takes a narrower range than a double, but it's more accurate. Therefore, there is no implicit conversion between decimal and double--the conversion in one direction may overflow, and the precision may be lost in another direction. You have to use an explicit conversion.
When a variable is defined and assigned to it, the M suffix is used to indicate that it is a decimal type:
Decimal decmyvalue = 1.0m;
If M is omitted, it is recognized by the compiler as a double before the variable is assigned.

4.1.2 Structure Type
A struct type can declare constructors, constants, fields, methods, properties, indexes, operators, and nested types. Although the listed functionality looks like a mature class, in C #, the difference between a struct and a class is that the struct is a value type, and the class is a reference type. In contrast to C + +, a class can be defined here with a struct keyword.
The main idea of using structs is to create small objects, such as Point and FileInfo, and so on. You can save memory because there is no additional reference generated as required by the class object. For example, this can cause significant differences when declaring an array that contains thousands of objects.
Listing 4.1 contains a simple structure named IP that represents an IP address that uses the byte type of 4 fields. I do not include methods, and so on, as these work as with classes, will be described in detail in the next chapter.

Listing 4.1 defines a simple structure

1:using System;
2:
3:struct IP
4: {
5:public byte b1,b2,b3,b4;
6:}
7:
8:class Test
9: {
10:public static void Main ()
11: {
12:ip MyIP;
13:MYIP.B1 = 192;
14:MYIP.B2 = 168;
15:myip.b3 = 1;
16:MYIP.B4 = 101;
17:console.write ("{0}.{ 1}. ", MYIP.B1,MYIP.B2);
18:console.write ("{0}.{ 1} ", myip.b3,myip.b4);
19:}
20:}

4.1.3 Enumeration types
When you want to declare a unique type consisting of a specified set of constants, the enumeration type is exactly what you are looking for. In the simplest form, it may look like this:
Enum MonthNames {January, February, March, April};
Because I am accustomed to the default settings, the enumeration element is int and the first element is 0 value. Each successive element is incremented by 1. If you want to assign a value directly to the first element, you can set it to 1 as follows:
Enum MonthNames {january=1, February, March, April};
If you want to assign arbitrary values to each element--or even the same value--that's not a problem:
Enum MonthNames {january=31, february=28, march=31, april=30};
The final selection is different from the int data type. You can assign this value in a single statement:
Enum Monthnames:byte {january=31, february=28, march=31, april=30};
The types you can use are limited to long, int, short, and byte.


4.2 Reference types
Reference types do not store the actual data they represent, but they store references to the actual data, as opposed to value types. The following reference types are provided in C # for you to use:
• Object Type
• Class type
• interface
• Representative Yuan
• String type
• array

4.2.1 Object Type
An object type is the mother of all types-it is the most fundamental base class for other types. Because it is the base class for all objects, you can assign any type of value to it. For example, an integral type:
Object theobj = 123;
Give all C + + programmers A warning: object is not equivalent to the void* you may be looking for. Anyway, it's always a good idea to forget the pointers.
When a value type is framed (exploited as an object), the object type is used. This chapter will discuss the box and the elimination box later.

4.2.2 Class type
A class type can contain data members, function members, and nested types. Data members are constants, fields, and events. Function members include methods, properties, indexes, operators, constructors, and destructors. The functions of classes and structs are very similar, but as mentioned earlier, structs are value types and classes are reference types.
Only single inheritance is allowed compared to C + +. (You cannot have multiple base classes that derive a new object.) However, a class in C # can be derived from multiple interfaces, which are described in the next section.
The fifth chapter "Class" is devoted to the use of class programming. This section is only intended to give a complete picture of where the C # class fits into the type diagram.

4.2.3 Interface
An interface declares a reference type that has only abstract members. Similar concepts in C + + are: Members of a struct, and the method equals 0. If you don't know anything about those concepts, here's what an interface in C # actually does. Only the method flags exist, but no code is executed at all. This implies that an interface cannot be instantiated, and only an object derived from that interface can be instantiated.
You can define methods, properties, and indexes in one port. So, comparing a class, what is the particularity of an interface? When you define a class, you can derive from multiple interfaces, and you can derive from only one class.
You might ask, "OK, but I have to implement all the interface members, so what can I get from this approach?" I want to cite one from. NET Example: Many classes implement the IDictionary interface. You can use a simple type to transform the Access interface:
IDictionary mydict = (IDictionary) someobjectthatsupportsit;
Now your code has access to the dictionary. But wait, I say many classes can implement this interface--so you can reuse code in multiple places to access the IDictionary interface! Once learned, any place can be used.
When you decide to use interfaces in class design, it's a good idea to learn more about object-oriented design. This book cannot teach you these concepts, but you can learn how to create interfaces. The following code snippet defines the interface Iface, which has only one method:
Interface Iface
{
void Showmyface ();
}
As I mentioned, you cannot instantiate an object from this definition, but you can derive a class from it. Therefore, the class must implement the Showmyface abstract method:
Class Cface:iface
{
public void Showmyface ()
{
Console.WriteLine ("Implementation");
}
}

The difference between an interface member and a class member is that an interface member cannot be implemented. Therefore, I do not want to mention this again in the next chapter.

4.2.4 Representative Yuan
A representative element encapsulates a method that has some flags. Basically, the representation element is a safe version of type safety and function pointers (callback functionality). Both static and instance methods can be encapsulated simultaneously in a representative instance.
Although you can use delegates as a method, their main purpose is to have a class of events. Again, I want to lead you to the next chapter, where the class will be discussed in detail.
4.2.5 String Type
C programmers may be surprised, but of course, C # has a basic string type for manipulating string data. The string class derives directly from the object, and it is sealed, which means that the class cannot be derived from it again. Like other types, a string is an alias for a predefined class system string.
It's very simple to use:
String myString = "some text";
Merging strings is just as simple:
String myString = "some text" + "and a bit more";
And if you want to access a single character, all you have to do is access the subscript:
Char chfirst = mystring[0];
When comparing two strings for equality, simply use "= =" to compare the operator.
if (myString = = yourstring) ...
I just want to mention that although a string is a reference type, the comparison is a comparison value rather than a reference (memory address).
The string type is used for almost every example of this book, and in these routines I'll introduce you to some of the most interesting methods that are exposed by string objects.
4.2.6 Array
An array contains variables that are accessed by calculating the subscript. All variables contained in an array and treated as elements must be of the same type. This type is naturally referred to as "array type". An array can store an integer object, a string object, or any object you propose.
The number of dimensions of an array is called rank, which determines the subscript number of the associated array element. The most commonly used array is a one-dimensional array (the first row). A multidimensional array has a number of rows greater than 1. The subscript of each dimension begins at 0, and finally the length of the dimension is reduced by 1.
Should have sufficient theoretical support. Let's take a look at an array initialized with an array initializer (initializer):
String[] Arrlanguages = {"C", "C + +", "C #"};
The shorthand effect equates to the following:
Arrlanguages[0]= "C"; Arrlanguages[1]= "C + +"; Arrlanguages[2]= "C #";
And the compiler did all the work for you. Of course, it will also work for multidimensional array initializers:
int[,] arr = {{0,1}, {2,3}, {4,5}};
It is the following shorthand:
arr[0,0] = 0; arr[0,1] = 1;
arr[1,0] = 2; arr[1,1] = 3;
arr[2,0] = 4; arr[2,1] = 5;
If you don't want to initialize an array in advance, but you know its size, the declaration is like this:
int[,] Myarr = new int[5,3];
If the size of the array must be computed dynamically, the statement used for the array creation can be written like this:
int nVar = 5;
int[] Arrtoo = new Int[nvar];
As I stated at the beginning of this section, you can plug anything into an array as long as all of the element types are the same. So, if you want to put anything in an array, declare its type as an object:

4.3 Plus box and extinction frame
In the course of this chapter, I have given a variety of value types and reference types. Because of the speed, you use the value type--it has nothing to do with the memory block that occupies a certain amount of space. However, sometimes the convenience of an object is as good as a value type.
This is where the box and the box are mounted on the stage, and the frame and the frame are the core concepts of the C # type system. This mechanism forms a bundled connection between a value type and a reference type by allowing a value type to be converted to a type object or converted from a type object to a value type. Everything is an object after all--but only when they are needed.
4.3.1 Add box Conversion
Add a Value box to implicitly convert any value type to a type object. When a value type is framed, an object instance is assigned, and the value of the value type is copied to the new object.
See the following example:
int nfunny = 2000;
Object ofunny = Nfunny;
The assignment of the second row implies that a box operation is invoked. The value of the Nfunny integer variable is copied to the Ofunny object. Both the integer variable and the object variable are present in the stack, but the value of the object stays in the heap.
So what does it imply? Their values are independent of each other-there is no connection between them. (Ofunny does not refer to a Nfunny value.) The following code illustrates the result:
int nfunny = 2000;
Object ofunny = Nfunny;
Ofunny = 2001;
Console.WriteLine ("{0} {1}", Nfunny, Ofunny);
When the code changes the value of the Ofunny, the Nfunny value does not change. As long as you have this copy action in your head, you will be able to use the object function of the value type to play your great advantage!
4.3.2 Box Conversion
The extinction box is explicit when compared to a box--you must tell the compiler which value type you want to extract from the object. When the extinction action is performed, C # detects that the requested value type is actually stored in the object instance. After a successful checksum, the value is eliminated.

This is how the elimination box is executed:
int nfunny = 2000;
Object ofunny = Nfunny;
int nnotsofunny = (int) Ofunny;

If a double value is requested incorrectly
Double Nnotsofunny = (double) Ofunny;
The common language runtime (Common Language Runtime, abbreviated CLR) will throw a InvalidCastException exception. You can learn more about exception handling in the 7th Chapter, "Exception Handling".

4.4 Summary
In this chapter, you learn the various types that are used in C #. Simple value types include integers, booleans, floating-point types, and decimal forms. You will use a number of types very often, mathematical and financial calculations, and logical expressions.
Before I introduce the reference type, I show a struct type that looks like a class. It works almost like a class, but it's just a value type, which makes it more suitable for situations where a lot of small objects are needed.
The reference type starts at the Objedt itself of the parent of all objects. object is the base class for all objects in C #, and it is also used for box and extinction of value types. In addition, I let you have a taste of the representation of elements, strings, and arrays.
The type that makes C # programmers very proud is the class. It's the heart of C # object-oriented programming, and the next chapter is a complete chapter that allows you to quickly understand this exciting and powerful type.

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.