C# 隐式转换和显示转换
显式转换implicit关键字告诉编译器,在源代码中不必做显示的转型就可以产生调用转换操作符方法的代码.
隐式转换implicit关键字告诉编译器只有当源代码中指定了显示的转型时,才产生调用转换操作符方法的代码.
隐式转换可能在各种情况下发生,包括功能成员调用,表达式执行和赋值。
显式转换可以在强制类型转换表达式中发生。
用户定义的隐式转换应该被设计成不会抛出异常而且不会丢掉信息。
如果一个用户定义的转换将产生一个异常(例如因为源变量超出了范围)或丢掉信息(例如丢掉高位),那么这个转换应该被定义为一个显式转换。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace 显示转换和隐式转换 8 { 9 public class Rectangle 10 { 11 public double Length { get; set; } 12 13 public double Width { get; set; } 14 15 /// <summary> 16 /// 重载隐式转换操作符 17 /// </summary> 18 /// <param name="v"></param> 19 public static implicit operator Rectangle(Square v) 20 { 21 //正方形在任意条件下都能转换为矩形,所以可以实现隐式转换 22 return new Rectangle() { Width = v.Length, Length = v.Length }; 23 } 24 } 25 26 public class Square 27 { 28 public double Length { get; set; } 29 30 /// <summary> 31 /// 重载隐式转换操作符 32 /// </summary> 33 /// <param name="v"></param> 34 public static explicit operator Square(Rectangle v) 35 { 36 //正方形是矩形的一个子集,所以把矩形转换为正方形,有可能会丢失信息 37 //所以最好是实现显示转换。这样当转换条件不够时,就能抛出异常 38 if (v.Width != v.Length) 39 { 40 throw new InvalidCastException("长度和宽度不相等,无法转换"); 41 } 42 return new Square() { Length = v.Length }; 43 } 44 } 45 46 internal class Program 47 { 48 public static void RectToSquaImplicit(Rectangle rect, Square squa) 49 { 50 rect = squa;//把矩形隐式转换为正方形 51 52 Console.WriteLine($"{rect.Width},{rect.Length}"); 53 } 54 55 public static void SquaTpRectToExplicit(Square squa, Rectangle rect) 56 { 57 squa = (Square)rect;//把矩形隐式转换为正方形 58 59 Console.WriteLine($"{squa.Length}"); 60 } 61 62 private static void Main(string[] args) 63 { 64 var rect1 = new Rectangle() { Length = 60, Width = 60 }; 65 var rect2 = new Rectangle() { Length = 100, Width = 75 }; 66 67 var squa = new Square() { Length = 50, }; 68 69 RectToSquaImplicit(rect1, squa); 70 SquaTpRectToExplicit(squa, rect1);//转换成功 71 72 SquaTpRectToExplicit(squa, rect2);//转换失败,抛出异常 73 } 74 } 75 }