Review 1:
1: Numerical Conversion. For built-in values (sbyte, int, float, etc.), if a large value is stored in a small container, an explicit conversion is required, this may cause data loss. This actually tells the compiler:
Ignore me. I know what I am doing. In turn, if you try to put a small type into the specified target type without losing data, it will automatically perform implicit conversion:
Int a = 123;
Long B =;
Int c = (int) B;
2: class type conversion:
The class type can be associated through the traditional inheritance relationship (is-a relationship. In this case, the C # conversion process allows us to forcibly convert the type to the upper or lower levels in the class hierarchy.
How to convert two unrelated types:
Definition class Rectangle
Public class Rectangle
{
Public int Width {get; set ;}
Public int Height {get; set ;}
Public Rectangle (){}
Public Rectangle (int w, int h)
{
This. Width = w;
This. Height = h;
}
Public void Draw ()
{
For (int I = 0; I <Width; I ++)
{
For (int j = 0; j <Height; j ++)
{
Console. Write ("*");
}
Console. WriteLine ();
}
}
Public override string ToString ()
{
Return string. Format ("[Width is: {0}, Height is: {1}]", Width, Height );
}
// Define an implicit type conversion routine here
Public static implicit operator Rectangle (Square s)
{
Rectangle r = new Rectangle ();
R. Width = s. Length;
R. Height = s. Length * 2;
Return r;
}
}
Define Square
public class Square
{
public int Length { get; set; }
public Square(int l)
{
Length = l;
}
public Square() { }
public void Draw()
{
for (int i = 0; i < Length; i++)
{
for (int j = 0; j < Length; j++)
{
Console.Write(" *");
}
Console.WriteLine();
}
}
public override string ToString()
{
return string.Format("[Length is {0}]",Length);
}
Convert a rectangle to a square
Note that this version of the Square type defines a display conversion operator. Like the heavy-load operator process, the conversion routine uses C # operater combined with eplicit
It must be static. The input parameter is the object to be converted, and the operator type is the type object to be converted.
Objectively speaking, converting Square to int is not the most intuitive operation. However, this really makes us find that the custom conversion routine is very important:
Reload custom type conversion
public static explicit operator Square(Rectangle r)
{
Square s = new Square();
s.Length = r.Height;
return s;
}
public static explicit operator Square(int sideLength)
{
Square newSq = new Square();
newSq.Length = sideLength;
return newSq;
}
public static explicit operator int(Square s)
{
return s.Length;
}
}
As long as the code syntax is correctly written, the compiler does not care about the conversion from anything to anything.
Running result: