Security conversions for data types

Source: Internet
Author: User
One, packing and unpacking
1.1: Packing
A variable of type object can reference any object of any reference type, or it can refer to a value type, for example:
int i=42;
Object o=i;

I is a value type, so it exists in the stack, joins the O direct reference I, then the reference will be the stack. However, all references must refer to the objects on the heap, and it is not allowed if the data on the stack is a serious impediment to the robustness of the runtime and creates a potential security vulnerability. So what actually happens is the "runtime" allocates a small piece of memory on the heap, and then a copy of the value in I is copied to this memory, and finally let o refer to the copy. This behavior of automatically copying a data item from the stack to the heap becomes boxed (Boxing).
1.2: Remove the box
In order to access the boxed value, it must be coerced for type conversion (CAST), which checks whether a type can be safely converted to another type.

int i=42;
Object o=i;//boxed
i= (int) o//compiled successfully
The compiler found that the type of I specified is int, so code is generated at run time to check what the O actually refers to. It may refer to anything, and it doesn't really refer to an int because you say o references an int when you force a type conversion.
If o really references a boxed int, and all conditions are met, the coercion type conversion succeeds, and the compiler-generated code is extracted from the boxed int.
However, if o refers to an int that is not boxed, a type mismatch will occur and a InvalidCastException exception will be thrown, following is an example of a unboxing failure:
Circle c= New Circle ();
Object o=c;//boxed
int i= (int) o//compilation error
Boxing and unboxing can have a large overhead because they involve a lot of checking and require allocating additional heap (heap) memory; Boxing is useful, but abuse can seriously affect program performance. Then there is another technique-generics-that is similar to boxing.
two, is and as operators
You can use the IS operator to verify that the type of the object is what you want, as follows:
            Signalgenerator newsignal = new Signalgenerator ();
            Object o = newsignal;
            If (O is Signalgenerator)
            {
                Signalgenerator temp = (signalgenerator) o;
            }
The two operands of the IS operator, the left is a reference to an object, and the right side is a type name. If the object on the left is the right type, the is expression evaluates to True, and vice versa. In other words, the above code will only proceed to convert the reference variable O to signalgenerator only if it is determined that the conversion will succeed.
The as operator acts as a role similar to the IS operator, except for a slightly reduced function. You can use the AS operator as follows:
            Signalgenerator newsignal = new Signalgenerator ();
            Object o = newsignal;
            Signalgenerator temp = o as signalgenerator;
            if (temp!=null)
            {  
            }
As is the operator of a type conversion, if the conversion fails, the TEMP value is null, otherwise, the value of O.
An IS expression is used to determine whether an object is a specified type, and as is to convert an object type to a specified type and, if successful, to assign a value or null.
Iii. implicit conversions and explicit conversions
3.1: Implicit conversions
An implicit numeric conversion is actually a conversion from a low precision numeric type to a high precision numeric type. is a system-default conversion that is not required to be specifically stated or used in a special way. During an implicit conversion process, the compiler can safely perform the conversion without having to examine the transformation in detail. The conversion may not be successful and may throw an exception.
3.2: Explicit conversions
Three display conversion methods commonly used in C #:
(TypeName) ValueName, is a general method;
The Convert class provides a flexible type conversion package;
Parse method, which is suitable for conversions to numeric types.
For example, (int), Int32.Parse () and Convert.ToInt32 (). So what's the difference between three methods?
The int keyword represents an integral type, 32-bit, and its. NET Framework type is System.Int32.
(int) means that using an explicit cast is a type conversion. Implicit conversions can be used when we are from type int to long, float, double, or decimal, but when we convert from a long type to an int type we need to use an explicit cast, otherwise a compilation error will occur. That is, this conversion, when compiled, ensures that there is a display transformation relationship, and if it does not exist, it is prompted that it cannot be converted.
Int32.Parse () indicates that the string of numbers is converted to a 32-bit signed integer and is part of the content conversion. As long as it is a string, can be converted to the past, as to whether it is correct, the running process will be prompted whether the error:
A common method for us: public static int Parse (string).
Throws a ArgumentNullException exception if the string is empty;
Throws a FormatException exception if the string is not in the correct format;
If the value of string is less than MinValue or a number greater than MaxValue, the OverflowException exception is thrown.
Convert.ToInt32 () You can convert the value of multiple types (including object reference types) to type int because it has many overloaded versions:
public static int ToInt32 (object);
public static int ToInt32 (BOOL);
public static int ToInt32 (byte);
public static int ToInt32 (char);
public static int ToInt32 (decimal);
public static int ToInt32 (double);
public static int ToInt32 (short);
public static int ToInt32 (long);
public static int ToInt32 (sbyte);
public static int ToInt32 (string);
......
(int) and Int32.Parse (), the application of Convert.ToInt32 () give a few examples:
Example one:
Long longtype = 100;
int inttype = Longtype; Error, you need to use an explicit cast
int inttype = (int) longtype; Correct, explicit casts are used
Example two:
string stringtype = "12345";
int inttype = (int) StringType; Error, String type cannot be directly converted to int type
int inttype = Int32.Parse (StringType); That's right
Example three:
Long longtype = 100;
string stringtype = "12345";
Object objectType = "54321";
int inttype = Convert.ToInt32 (Longtype); That's right
int inttype = Convert.ToInt32 (StringType); That's right
int inttype = Convert.ToInt32 (ObjectType); That's right
Example four:
Double Doubletype = Int32.MaxValue + 1.011;
int inttype = (int) doubletype; Although it runs correctly, it gets the wrong result
int inttype = Convert.ToInt32 (doubletype)//Throw OverflowException exception
(int) and Int32.Parse (), Convert.ToInt32 () The difference between:
The first is used in an explicit cast on a long or floating-point type to an int type, but if the value being converted is greater than Int32.MaxValue or less than int32.minvalue, then an incorrect result is obtained.
The second is used in a string to the int type conversion process that matches the number format, and the corresponding exception can be thrown for the wrong string number format.
The third can convert several types of values to an int type, or you can throw a corresponding exception to the wrong value.
Regardless of the type of numerical conversion, the accuracy of numerical values is a problem we must consider.
When converting a char to an int using Convert.ToInt32 (), the Ascci code of this char is given to the past rather than the number, such as:
char c = ' 1 ';
int i;
i = Convert.ToInt32 (c); Matters needing attention in Char
The value of I is 49, and the ASCII code is 1.
To want 1, you can use a string type, such as:
String str= "1";
int i;
i = Int. Parse (str);
i = Convert.ToInt32 (str); The value of I is 1 instead of the 1 ASCII code.
Explicit conversion requirements for implicit conversions are of the same type, that is, the two data types must be compatible, the implicit conversions are up (quite a subclass of the parent class), and the coercion type conversion is a downward transition (rather a parent-class rotor Class), just as a double can contain an int.
Casts can be of the same type, as Class1 and Class2 siblings, and both are parsed on the content. Convert.ToInt32 and Int.parse are casts, int. Parse is converting a string to int (this is a lot of situations that may be optimized or just for convenience, processing logic), and Convert.ToInt32 is the conversion of objects that inherit from object to int (18 overloads). Like an object, you want to convert it to int, with Int. Parse can not, to use Convert.ToInt32.
Resources:
http://blog.csdn.net/lerit/article/details/4441971

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.