不忘本~explicit和implicit修饰符
部分内容来自MSDN
implicit 关键字用于声明隐式的用户定义类型转换运算符。如果转换过程可以确保不会造成数据丢失,则可使用该关键字在用户定义类型和其他类型之间进行隐式转换。
1 class Digit 2 3 { 4 5 public Digit(double d) { val = d; } 6 7 public double val; 8 9 10 11 12 13 // User-defined conversion from Digit to double 14 15 public static implicit operator double(Digit d) 16 17 { 18 19 return d.val; 20 21 } 22 23 // User-defined conversion from double to Digit 24 25 public static implicit operator Digit(double d) 26 27 { 28 29 return new Digit(d); 30 31 } 32 33 } 34 35 class Program 36 37 { 38 39 static void Main(string[] args) 40 41 { 42 43 Digit dig = new Digit(7); 44 45 //This call invokes the implicit "double" operator 46 47 double num = dig; 48 49 //This call invokes the implicit "Digit" operator 50 51 Digit dig2 = 12; 52 53 Console.WriteLine("num = {0} dig2 = {1}", num, dig2.val); 54 55 Console.ReadLine(); 56 57 } 58 59 }
explicit 关键字用于声明必须使用强制转换来调用的用户定义的类型转换运算符
1 // cs_keyword_explicit_temp.cs 2 using System; 3 class Celsius 4 { 5 public Celsius(float temp) 6 { 7 degrees = temp; 8 } 9 public static explicit operator Fahrenheit(Celsius c) 10 { 11 return new Fahrenheit((9.0f / 5.0f) * c.degrees + 32); 12 } 13 public float Degrees 14 { 15 get { return degrees; } 16 } 17 private float degrees; 18 } 19 20 class Fahrenheit 21 { 22 public Fahrenheit(float temp) 23 { 24 degrees = temp; 25 } 26 public static explicit operator Celsius(Fahrenheit f) 27 { 28 return new Celsius((5.0f / 9.0f) * (f.degrees - 32)); 29 } 30 public float Degrees 31 { 32 get { return degrees; } 33 } 34 private float degrees; 35 } 36 37 class MainClass 38 { 39 static void Main() 40 { 41 Fahrenheit f = new Fahrenheit(100.0f); 42 Console.Write("{0} fahrenheit", f.Degrees); 43 Celsius c = (Celsius)f; 44 Console.Write(" = {0} celsius", c.Degrees); 45 Fahrenheit f2 = (Fahrenheit)c; 46 Console.WriteLine(" = {0} fahrenheit", f2.Degrees); 47 } 48 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示