C#学习笔记 -- 自定义类型转换
-
可以位自己的类和结构定义隐式转换和显式转换, 这里允许把用户定义类型的对象转换成某个其他类型, 反之亦然
-
隐式转换与显式转换
-
对于转换, 当决定在特定上下文中使用特定类型时, 如有必要, 编译器会自动执行转换
-
对于显式转换, 编译器只在使用显式转换运算符时才执行转换
-
(1)隐式转换
-
转换的方法必须是
public static
的 -
implicit
隐式转换
public static implicit operator 目标类型(原数据类型 形参) { ... return 目标类型返回值; }
例子
class LimitedInt { const int MaxValue = 100; const int MinValue = 0; private int theValue = 0; public int TheValue { set { if (value < MinValue) { theValue = MinValue; } else { theValue = value > MaxValue ? MaxValue : value; } } get { return theValue; } } public LimitedInt(int theValue) { TheValue = theValue; } public LimitedInt() { } //隐式转换 自定义类型转换 => int public static implicit operator int(LimitedInt li) { return li.TheValue; } //隐式转换 int => 自定义类型转换 public static implicit operator LimitedInt(int i) { return new LimitedInt(i); } }
static void Main(string[] args) { //914 limitedInt { //隐式的转换为自定义类型 LimitedInt limitedInt = 500; int i = limitedInt; Console.WriteLine($"自定义类型值为{limitedInt.TheValue}, int类型值为{i}"); //100 100 } }
(2)显式转换与强制转换运算符
-
转换的方法必须是
public static
的 -
explicit
隐式转换 -
强制转换符
目标类型 var1 = (目标类型) var2
-
必须配上强制转换运算符使用, 代表不得不实行转换时候进行转换类型
public static explicit operator 目标类型(原数据类型 形参) { ... return 目标类型返回值; }
例子
class LimitedInt { const int MaxValue = 100; const int MinValue = 0; private int theValue = 0; public int TheValue { set { if (value < MinValue) { theValue = MinValue; } else { theValue = value > MaxValue ? MaxValue : value; } } get { return theValue; } } public LimitedInt(int theValue) { TheValue = theValue; } public LimitedInt() { } //显式转换 自定义类型转换 => int public static explicit operator int(LimitedInt li) { return li.TheValue; } //显式转换 int => 自定义类型转换 public static explicit operator LimitedInt(int i) { return new LimitedInt(i); } }
static void Main(string[] args) { //914 limitedInt { //隐式的转换为自定义类型 LimitedInt limitedInt = (LimitedInt)500; int i = (int) limitedInt; Console.WriteLine($"自定义类型值为{limitedInt.TheValue}, int类型值为{i}"); //100 100 } }
注意
-
还有两个运算符接受一种类型的值, 并返回另一种不同的, 指定类型的值, is as
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律