Rule of type conversion (NET1.1 +), Rule net1.1

Source: Internet
Author: User

Rule of type conversion (NET1.1 +), Rule net1.1

[Question]

In the conversion of C # and Visual Basic, what are the usage and differences of the following conversions?

[C #]

long num = 12;
int n = (int)num;
int m = Convert.ToInt32(num);

[VB. NET]

Dim num As Long = 12
Dim n As Integer = num
n = CInt(num)
n= CType(num,Integer)
n = Convert.ToInt32(num)

[Incorrect answer]

There is no difference, because it can be converted normally after running.

[Positive solution]

There is no difference from the running results, because the question only gives some examples, not all. Many beginners are prone to the incorrect understanding of "taking it for granted. Let's first use C # as an example for comparison:

[C #]

long num = long.MaxValue;
int n = (int)num; …………………………①
int m = Convert.ToInt32(num); ………②

Note the example at ①, because I want to assign a long type to the int type. Therefore, in syntax, VS does not consider direct conversion unless you use the forced type conversion declaration. At the same time, because long. MaxValue is far greater than the range that int can accommodate, the value actually stored in n is overflow (that is, it is not the original value ).

If you comment out the ① sentence and run it separately, you will find an error. The prompt is that num is greater than the upper or lower limit of int, and run it separately. ① only because the string is truncated, no error message. Obviously, the conversion principle of Convert is to directly check whether the actually stored value of the variable to be converted (this article entitled num) can be used by another receiver (this article entitled m) accept -- if the value exceeds the range of the m type (that is, the MaxValue and MinValue of the int type), it is considered as an error.

In the same sample in VB. NET, we will do an experiment:

Dim num As Long = Long.MaxValue
Dim n As Integer = num…………………①
n = CInt(num) …………………………②
n= CType(num,Integer) ………………③
n = Convert.ToInt32(num)

As a result, no matter if you comment out other expressions and run the statements ①, ②, or ③ separately, the error "arithmetic operation causes overflow" will be thrown. It can be seen that in VB. NET, the syntax checks whether the converted value can be accommodated by the receiver after conversion. If not, an exception is thrown.

Come with a sentence-in fact,C #This can also be performed in forced conversion.VB. NETSame"Overflow"Detection, but the defaultC #YesUncheckedMechanism.You can useCheckedMechanism to achieve similarConvertSame conversion Effect. For example:

[C #]

Checked
{
Long num = long. MaxValue;
Int n = (int) num; // an error is thrown immediately after running, indicating that the result overflows.
}

[Summary]

1) C #Normal forced type conversion (similarC #In the first example), only syntax check is performed by default, and whether the actually converted value can be accepted is not checked unless explicitly placed"Checked"Block.

2) C #OrVB. NETOfConvertNot only checks the conversion type (becauseConvert. ToXXXOf"XXX"Is the type to be converted .)"Converted"Whether the value in the variable can be fully occupied by the converted variable.

3)C #The syntax is rigorous.=>Required for small type conversion"Explicit declaration"; Relatively speaking,VB. NETNo such rigorous syntax is required. ForVB. NETDirectly assign values"A = B"(EquivalentA = CType (B,). For the value type, B must consider the definition of an implicit or explicit conversion function (below ). However, CType is syntactically equivalent to A a = (A) B for "class". It is necessary to strictly check whether B can be converted to A (in either case: either B is the parent class of A, or A custom implicit/explicit conversion from B => A, otherwise A syntax error occurs. In addition, for the first type,If you want to ensure that the operation is normal, the entity class contained in B must be at least A or its subclass ).

4) In addition, VB. NET has a DirectCast conversion. The two objects it accepts must be classes and cannot be structures (even if the structure is user-defined implicit/explicit conversion ).

[Expansion]

1. Custom explicit and implicit conversions:

We now know the fact that.. NET Framework (C # and VB. NET), in the "type conversion", the class is based on the "ryth principle"-that is, the subclass is converted to the parent class; that is, the class without any relationship cannot be forcibly converted. Now the question is: int, double, and so on are all structures (structures cannot be inherited). How do they implement mutual conversion? In fact, C # Or VB. NET allows implicit and explicit conversions to be specified manually for two unrelated types (here referred to as "non-inheritance relationships. The syntax is as follows:

[C #]

Public static implicit/exclept operatorConverted type(Type before conversion Variable name)

[VB. NET]

Public Shared Widening/Narrowing Operator CType (Type before conversion Variable name)Converted type

This method is a custom value assignment symbol (=). It does not belong to any class instance. It is special, and some are similar to "Operator Overloading". Therefore, it is a static method, it is loaded immediately and automatically called upon running. "Implicit" is implicitly converted, and "exclipit" is explicitly converted (when the exclipit method is defined, the call must be written as: xxx = (type after conversion) variable name, just like long => int must be written in the form of (int) long variable ).

Any class inherits the ToString () method from its inherent parent class "object", but this method is not overwritten by default. Therefore, "namespace. Class Name" is returned ". We don't want to do this. The best result is that if we directly assign this class to a String and then output its main content through String. The following describes the problem through the simple "plural class:

[C #]

Public class Complex
{
Public double Real {get; set ;}
Public double Comnum {get; set ;}

Public static implicit operator string (Complex c)
{
// Prepare the string variable output after conversion
String result = string. Empty;

// If the real number is not equal to 0

If (c. Real! = 0)
{
// Splice the real part
Result + = c. Real. ToString ();
}

// Virtual part, if not equal to 0

If (c. Comnum! = 0)
{
// If the imaginary part is smaller than 0, it is output together with the negative number.
If (c. Comnum <0)
{
Result + = c. Comnum + "I ";
}
// If the imaginary part is greater than 0
Else if (c. Comnum> 0)
{
// If the real number is equal to 0, the imaginary part is directly output.
If (c. Real = 0.0)
{
Result = c. Comnum. ToString () + "I ";
}
// Otherwise, the preceding output contains the plus sign
Else
{
Result + = "+" + c. Comnum + "I ";

}
}
}
Return result;
}
}

[VB. NET]

Public Class Complex
Public Property Real () As Double
Get
Return m_Real
End Get
Set
M_Real = Value
End Set
End Property
Private m_Real As Double
Public Property Comnum () As Double
Get
Return m_Comnum
End Get
Set
M_Comnum = Value
End Set
End Property
Private m_Comnum As Double

Public Shared Widening Operator CType (c As Complex) As String
'The string variable to be output after conversion
Dim result As String = String. Empty
'If the real number is not equal to 0
If c. Real <> 0 Then
'Splice the real part
Result + = c. Real. ToString ()
End If

'Virtual part, if not equal to 0
If c. Comnum <> 0 Then
'If the imaginary part is less than 0, it is output together with the negative number.
If c. Comnum <0 Then
Result + = c. Comnum + "I"
'If the imaginary part is greater than 0
ElseIf c. Comnum> 0 Then
'If the real number is equal to 0, the imaginary part is directly output.
If c. Actual = 0.0 Then
Result = c. Comnum. ToString () & "I"
Else
'Otherwise, the preceding output contains the plus sign
Result + = "+" + c. Comnum & "I"
End If
End If
End If
Return result
End Operator
End Class

When calling (using the VS2008 or later syntax, you can create an object first and assign values to the object attributes one by one ):

[C #]

string s = new Complex { Real = 1.2, Comnum = 2.3 };
Console.WriteLine(s);
s = new Complex { Real = 0, Comnum = -2.5 };
Console.WriteLine(s);
s = new Complex { Real = -2.5, Comnum = 0 };
Console.WriteLine(s);
s = new Complex { Real = -2.5, Comnum = -2.5 };
Console.WriteLine(s);

[VB. NET]

Dim s As String = New Complex() With { _
Key .Real = 1.2, _
Key .Comnum = 2.3 _
}
Console.WriteLine(s)
s = New Complex() With { _
Key .Real = 0, _
Key .Comnum = -2.5 _
}
Console.WriteLine(s)
s = New Complex() With { _
Key .Real = -2.5, _
Key .Comnum = 0 _
}
Console.WriteLine(s)
s = New Complex() With { _
Key .Real = -2.5, _
Key .Comnum = -2.5 _
}
Console.WriteLine(s)

See it-a Custom Complex and string can be converted (Note: String is a sealed class and cannot exist in any other subclass ). So let's say --Without any other implicit or explicit conversions, the conversion between the two classes by default must follow"Lee's principles"(Subclass=>Parent class )..

If you convert "implicit" in the preceding example to "exclipit", call (for example only )--

String s = (string) new Complex {Real = 1.2, Comnum = 2.3 };

Here, we can answer the question in "expansion": the reason why the structure of the "irrelevant, not inherited" relationship can be converted to each other is that Microsoft has applied similar techniques, defines "implicit" and "Explicit" conversion methods for each structure (such as Int32. These structures can be implicitly or explicitly converted to each other. For example, Microsoft defines an explicit conversion rule from long to int for long and an implicit conversion rule for long to double (of course, you define long to int as implicit, defining long to double as explicit is not a problem ). So the question that comes out here is: when will implicit and exclept be defined?

Generally"Exception Principle"Make a judgment (the so-called"Exception Principle"That is to say, if a type is converted to a type without errors or data loss, we recommend that you useImplicitOtherwise, we recommend that you useExplicit(For example, int => long is always set, because int only occupies 4 bytes, and long is 8 bytes. It is always set. But in turn, overflow may occur, or the conversion is abnormal ).

Ii. Practical application of the "exception principle" in C # On the "syntax layer:

When it comes to conversion, C # is much more complex than VB. NET (it must go through the "Syntax" and "actual data" steps ). Let's take a look at the conversion rules of C # On the "syntax layer". Generally, you can remember the following rules (1. sybe, int, and long are signed types, byte, uint/char, and ulong are unsigned types. 2. From left to right, the range of values can be larger and larger. The range that char can represent is equivalent to uint, but the output is a character ):

Sbyte byte short ushort int uint/char long ulong float decimal double

1) Conversion rules between symbols: Large=>Small always implicit, small=>Always show.

2) Conversion rules between symbols: Large=>Small always implicit, small=>Always show.

3)Float, doubleAndDecimalAll use Explicit conversions.

4) All signed conversions to unsigned (including conversionsChar) All use Explicit conversions.

In fact, the general parent of these basic principles is derived from the "exception principle" (for example, the unsigned value may cause a numerical exception because there is no negative number, so forced conversion is required ).

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.