Demonstration and conversion of the C # tutorial [original]

Source: Internet
Author: User

As this chapter is the most basic part of this book, we also focus on learning methods and instructions for using tools such as Visual Studio.

  

A special class or method is required to complete the display conversion. For example

  

Long lo = 1; // declare a long variable

  

Byte B = Convert. ToByte (lo); // Convert using the Convert class

  

Short sh = (short) lo; // use strong type conversion

  

Int I = int. Parse (lo. ToString (); // use the Parse method in the type to convert

  

From the above example, we should easily think of a serious problem. Because all the above are downsized conversions. Whether the data or precision is lost in the process of downgrading or downgrading. Next we will create another instance. The procedure is as follows:

  

1. add a button to the Form1 form in the "type conversion and unpacking" project created above, and change the text on the button to "display conversion instance", 2-16;

  

2. Add a new Windows form to the "type conversion and unpacking" project created above. In Solution Explorer, right-click the project name of the new supervisor and choose add new item --> Add Windows form' to name the new form Xszh. cs. Add method 2-21

 

  

Figure 2-21

  

Xiaotian: How do you have so many projects in your solution from resource manager ??? I only have one.

  

Laotian: This is simple. You can choose to add a new project to the File menu of vs. This will add the new project to the solution. This will not be illustrated, and I will explore it myself.

  

3. Double-click the "show conversion instance" button and add the following code:

  

/// <Summary>

  

/// Double-click the event generated by the "show conversion instance" button. We only add two lines of code in the event.

  

/// This is the last time I commented on the automatically generated events. I don't know how to conquer the events.

  

/// </Summary>

  

/// <Param name = "sender"> event source </param>

  

/// <Param name = "e"> message </param>

  

Privatevoid button2_Click (object sender, EventArgs e)

  

{

  

Xszh xs = newXszh (); // the newly created Xszh form is actually a class.

  

Xs. Show (); // display the previously created form

  

}

  

4. Run F5. Click "show conversion instance" to see if a new form is displayed. If it succeeds, close the form and make sure VS stops debugging. (sometimes the computer is slow and the form is closed, but VS is still in the debugging status. This may cause the code to be read-only, even VS reports an error ). How can we ensure that, in VS debugging status, VS will add a tool bar named "debug" by default, 2-22

 

  

Figure 2-22

  

5. Right-click the Xszh form and choose Properties to change the Text attribute to "display conversion instance ".

  

TIPS: As this chapter is the most basic part of this book, we also focus on learning methods and instructions for using tools such as Visual Studio. Friends with basic knowledge can quickly skip this content. If you have no basic knowledge, do not simply accept the knowledge, imitate my practices and steps. You must think more about it. Why did Laotian demonstrate the instance. In fact, all of my processes and examples are based on my own self-taught experiences and experiences that many students make mistakes and are easy to ignore during the teaching process. So I believe it is definitely worth your reference.

  

For example, add a new project to Solution Explorer, add a new item to the project, modify the control properties, and double-click the control to generate Event code.

  

The prompt similar to modifying attributes will not be mentioned in the subsequent sections. I will try to find other attributes of each used control myself. As mentioned above, in the VS attribute panel, each attribute item is described, and you can use the instructions to explain the exercises.

  

6. Drag some Label controls on the form to display instructions and receive conversion results. Put a TextBox to enter the number to be converted. A button to execute the conversion. A GroupBox (in the container category of the Toolbox ). Final layout effect 2-23

 

  

Figure 2-23

  

7. Double-click "show me" and enter the following code in the event:

  

Int I = int. Parse (textBox1.Text); // conversion is required because textBox1.Text is of the string type.

  

// Convert the int type separately, and convert the result to the string type to the corresponding Label,

  

// Because the Label. Text type is also string, it must be converted to string before being handed over to the Label's Text attribute.

  

// The reason why we want to enclose (byte) I is that we want to convert the entire I to the result ToString of the byte type,

  

// If you do not include all (byte) I, the compiler will mistakenly assume that we want to set the strong type of I. ToString () to byte

  

Lbl_byte.Text = (byte) I). ToString ();

  

Lbl_cmd.text = (short) I). ToString ();

  

Lbl_long.Text = (long) I). ToString ();

  

Lbl_float.Text = (float) I). ToString ();

  

Lbl_double.Text = Convert. ToDouble (I). ToString ();

  

8. next, let's run the program. Remember to enter a number (a thin number, not a character or symbol, or a fat number, that is considered a character );

  

JOHN: I found that I was fooled by C. Because his conversion result is wrong, 2-24, long, and double are correct, and others are wrong. Why?

 

  

Figure 2-24

  

Hey hey, this is what others say is really tough. However, C # also provides verification methods. The keyword checked can be used to check whether data type conversion is secure. If it is not secure, the runtime will throw an overflow exception, as shown below:

  

Lbl_byte.Text = checked (byte) I). ToString ();

  

Lbl_cmd.text = checked (short) I). ToString ();

  

Lbl_long.Text = checked (long) I). ToString ();

  

Lbl_float.Text = checked (float) I). ToString ();

  

Lbl_double.Text = checked (Convert. ToDouble (I). ToString ());

  

Tian: I think the double type can contain decimal places, but an error occurs when I try to input decimal places.

  

Laotian: All explicit data type conversions may be insecure. Such code should be included in the application to process data type conversions that may fail. Later, the exception handling section introduces the structured exception handling using try and catch statements.

  

Using data type conversion can convert most data from one basic type to another. For example, add 0.5 to the price and convert the result to int:

  

Double price = 25.30;

  

Int approximatePrice = (int) (price + 0.5); // The value is 25, and 0.80 after the decimal point is lost

  

JOHN: Why is it lost?

  

Laotian: During this conversion process, all data after the decimal point will be lost. Therefore, if you want to use this modified price for more calculations, you 'd better not use this conversion. If you want to output an approximate value that has been fully calculated or partially calculated, this conversion is good if you do not want to use the data after the decimal point.

  

Explicit numeric conversion is used to convert any numeric type to any other numeric type through an explicit conversion expression. There is no implicit conversion for it. The following table shows the conversions.

  

From

  

Sbyte byte, ushort, uint, ulong, or char

  

Byte Sbyte or char

  

Short sbyte, byte, ushort, uint, ulong, or char

  

Ushort sbyte, byte, short, or char

  

Int sbyte, byte, short, ushort, uint, ulong, or char

  

Uint sbyte, byte, short, ushort, int or char

  

Long sbyte, byte, short, ushort, int, uint, ulong, or char

  

Ulong sbyte, byte, short, ushort, int, uint, long or char

  

Char sbyte, byte, or short

  

Float sbyte, byte, short, ushort, int, uint, long, ulong, char or decimal

  

Double sbyte, byte, short, ushort, int, uint, long, ulong, char, float, or decimal

  

Decimal sbyte, byte, short, ushort, int, uint, long, ulong, char, float, or double

  

Note the following points for display conversion:

  

Explicit numeric conversion may cause loss of precision or exceptions.

  

When a decimal value is converted to an integer, the value is rounded to the nearest integer to zero. OverflowException is triggered if the result integer is out of the range of the target type.

  

When you convert a double or float value to an integer, the value is truncated. If the integer value of the result exceeds the range of the target value, the result depends on the context of the overflow check. OverflowException is triggered in the checked context. In the unchecked context, the result is an unspecified target type value.

  

When double is converted to float, the double value is rounded to the nearest float value. If the double value is too small or too large to accommodate the target type, the result is zero or infinite.

  

When float or double is converted to decimal, the source value is converted to a decimal representation and rounded to the nearest number after 28th small numbers (if needed ). Depending on the source value, the following results may be generated:

  

If the source value cannot be expressed as decimal because it is too small, the result will be zero.

  

OverflowException is triggered if the source value is NaN (non-numeric value), infinity, or cannot be expressed as decimal due to an excessively large value.

  

When decimal is converted to float or double, the decimal value is rounded to the nearest double or float value.

  

To convert an empty type to a non-empty type, or to another empty type, but data may be lost, Explicit conversions must be used. It is important to use Explicit conversions when converting between elements with the same underlying basic types, such as int? Convert to int or float? To float. This is because the value of the null type can be null. A non-null type cannot represent this value. An explicit conversion can be performed between two non-empty types. However, if the value of the variable is null, an InvalidOperationException is thrown. For example:

  

Int? Aa = null; // set the value of aa to null.

  

Int B = (int) aa; // an exception is thrown. Like MSSQL, null is unknown in C #.

  

With explicit data type conversion and careful use of this technology, you can convert any instance of a simple value type to another type. However, there are some limitations in explicit type conversion, such as value type, which can only be converted between numeric, char, and enum types. You cannot directly convert the Boolean data type to another type, or convert other types to the Boolean data type.

  

If you need to convert between numbers and strings, the. NET Class Library provides some methods. The Object class has a ToString () method, which is overwritten in all. NET pre-defined types and returns the string representation of the Object:

  

Int I = 10;

  

String s = I. ToString ();

  

To analyze a string and obtain a number or Boolean value, you can use the Parse method supported by all predefined value types:

  

String s = "100 ";

  

Int I = int. Parse (s );

  

Xiaotian: it seems that this conversion is more fun, but when you say this, I think there are still many unclear points. However, I think the example you taught me above is too painful. Every time I run a program, I need to jump to a form that is completely unnecessary. But I don't want to create a project for every example.

  

Lao Tian: Yes. I want to practice more. As for the problem of skipping a useless form every time, it is a very good solution. You only need to modify the startup class in the project's Program. cs consumer, 2-25

 

  

Figure 2-25

  

Xiaotian: It's time to clean up. I plan to create 10 instances. Try one by one based on the many predefined types written above.

  

Laotian: If you have tried it one by one, and the comments have been made clear, you can leave it as a database that you can spare at any time.

  

In addition, we provide another learning method (from this example, you should consider the opposite, rather than simply describing the knowledge points), as shown in the following example:

  

Int a = 123; // declare int type variable

  

Short B = 321; // declare the short type variable B

  

Var c = a + B; // Add two variables of Different Types

  

Console. WriteLine (c. GetType (); // What type is the sum of values of Mixed Variables? Why?

  

Of course, if you want to, you can upload your exercises to the learning website specified at the end of this book to share your experiences with you.

  

TIPS: In the beginner's stage, commenting is actually a review process for further organizing ideas and enhancing impressions. Because when you make comments, You have to organize your own learning experience, and you have to read a book again to prove your understanding. Only when you can correctly write comments of every piece of code and the ideas of every piece of code can you really understand this knowledge point.

  

Do not copy the code according to the book. If you learn this way, I am here to tell you very seriously: "You should learn other things earlier. You can't do programming ". Because you can't learn this way, and you can't actually learn it. The most important thing is that you have not said that my book has not been written.

  

This article is a new one. For more information, see the source and author!

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.