FROM P169
Part1 用户定义的类型
用户定义的转换将在以后详细介绍,不过由于它们是运算符,在此先提一下。
□可以为自己的类和结构定义隐式转换和显式转换。这云讯把用户定义类型的对象转换成某个其他类型,反之亦然。
□C#提供隐式转换和显示转换。
--对于隐式转换,当决定在特定上下文中使用特定类型时,如有必要,编译器会自动执行转换。
--对于显式转换,编译器只在使用显式转换运算符时才执行转换。
声明隐式转换的语法如下。public和static修饰符是所有用户定义的转换所必需的。显式转换的语法与之相同,但要用explicit替换掉implicit。
1 public static implicit operator TargetType(SourceType Identifier) 2 { 3 …… 4 return ObjectOfTargetType; 5 }
具体示例:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace review 8 { 9 class LimitedInt 10 { 11 const int MaxValue = 100; 12 const int MinValue = 0; 13 public static implicit operator int (LimitedInt li) //将LimitedInt转换为int 14 { 15 return li.TheValue; 16 } 17 public static implicit operator LimitedInt(int x) //将int转换为LimitedInt 18 { 19 LimitedInt li = new LimitedInt(); 20 li.TheValue = x; 21 return li; 22 } 23 /* 24 * 显式类型转换部分 25 public static explicit operator int(LimitedInt li) //显式将LimitedInt转换为int 26 { 27 return li.TheValue; 28 } 29 public static explicit operator LimitedInt(int x) //显式将int转换为LimitedInt 30 { 31 LimitedInt li = new LimitedInt(); 32 li.TheValue = x; 33 return li; 34 } 35 */ 36 private int _thevalue = 0; 37 public int TheValue 38 { 39 get { return _thevalue;} 40 set 41 { 42 if (value < MinValue) 43 _thevalue = 0; 44 else 45 _thevalue = value > MaxValue ? MaxValue : value; 46 } 47 } 48 } 49 class Program 50 { 51 static void Main(string[] args) 52 { 53 LimitedInt li = 500;//将500转换为LimitedInt 54 int value = li;//将LimitedInt转换为int 55 Console.WriteLine("li:{0},value: {1}", li.TheValue, value); 56 Console.Read(); 57 } 58 } 59 } 60 /* 61 * 输出如下: 62 * li:100,value: 100 63 * */
无法同时对一种转换声明显式和隐式。如果声明为了explicit,则每次实行转换时都必须显式使用转换运算符。
e.g. LimitedInt li=(LimitedInt)500;
另外有两个运算符,接受一种类型的值,并返回另一种不同的,指定类型的值。就是is运算符和as运算符,将在以后提到。
Part2 运算符重载
□运算符重载只能用于类和结构。
□为类或结构重载一个运算符x,可以声明一个名称为operator x的方法并实现它的行为(例如: operator +和operator -等)。
一元运算符的重载方法带一个单独的class或struct类型的参数。
二元运算符的重载方法带两个参数,其中至少有一个必须是class或struct类型。
例子:
1 public static LimitedInt operator - (LimitedInt x) 2 public static LimitedInt operator + (LimitedInt x,double y)
运算符重载不能做下面的事情:
□创建新运算符
□改变运算符的语法
□重新定义运算符如何处理预定义类型
□改变运算符的优先级和结合性