回顾1:
1:数值转换,对于内建数值(sbyte,int,float等),如果在较小容器中存储较大的数值,就需要一个显式转换,因为这可能导致数据丢失。这实际上就是告诉编译器:
别理我,我知道我在做什么。反过来,如果试图将较小类型放到指定目标类型中时不会丢失数据,将 自动进行隐式转换:
int a=123;
long b=a;
int c=(int)b;
2:类类型转换:
类类型可通过传统的继承关系(is-a关系)关联起来。这时,C#转换过程允许我们向类层次结构中的上级或下级进行强制类型转换。
而当两个没有关系的两个类型时怎么转换呢如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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);
}
//在这定义个隐式类型转换例程
public static implicit operator Rectangle(Square s)
{
Rectangle r = new Rectangle();
r.Width = s.Length;
r.Height = s.Length * 2;
return r;
}
}
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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);
}
矩形可显示转换为正方形
注意,Square类型的这个版本定义了一个显示转换操作符。如同重载操作符过程一样,转换例程使用C#operater 结合eplicit
而且必须为静态的。传入参数是要转换的实体,而操作符类型是要转换后的类型实体。
客观来讲,将Square转换为int可能不是最直观的操作。不过,这确实让我们发现关于自定义转换例程非常重要的一点:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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;
}
}
只要代码语法书写正确,编译器并不关心由什么转换成什么。
运行结果: