在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
本次主要学习了一下C#中自定义类型的转换,一些转换c#默认是不能够转换的,所以这个时候就需要用户自己来定义需要转换的方式,也就是自定义的类型转换方式,用户自定义类型转换这里实现了两种,一种是显式的转换,一种是隐式的转换,再就是操作符的重载了。涉及到的关键字主要有:implicit(隐式),explicit(显式),operator(操作符),在代码中我们还要注意另一些关键字,如static哪里下面是代码部分:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OperatorClass { class Program { static void Main(string[] args) { Console.WriteLine("隐式转换:"); int testInt; //隐式转换 TransformTypeInt test = new TransformTypeInt(); //1. test = -200; Console.WriteLine(test.SourceInt); //2. test = 300; testInt = test; Console.WriteLine(testInt); Console.WriteLine(); Console.WriteLine("显式转换:"); //显式转换 string testStr; ExplicitTrans str = new ExplicitTrans(); //str = "HelloWorld"; str = (ExplicitTrans)"HelloWorld"; Console.WriteLine(str.SourceStr); testStr =(string)str; Console.WriteLine(testStr); Console.WriteLine(); Console.WriteLine("操作符重写:"); TransformTypeInt var1 = new TransformTypeInt(); TransformTypeInt var2 = new TransformTypeInt(); TransformTypeInt var = new TransformTypeInt(); var1 = 63; var2 = 78; var = var1 + var2; Console.WriteLine(var.SourceInt); Console.ReadKey(); } } /// <summary> /// 隐式转换类 /// </summary> //从一种类型转换到另一种类型 class TransformTypeInt { private int sourceInt=0; public int SourceInt { get { //返回一个大于零的数 return sourceInt > 0 ? sourceInt :0; } set { sourceInt = value; } } /// <summary> /// 隐式的转换 /// </summary> /// <param name="source"></param> //隐式转换,将TransformTypeInt转为int public static implicit operator int(TransformTypeInt source) { return source.SourceInt; } //隐式转换,将int转换为TransformTypeInt; public static implicit operator TransformTypeInt(int source) { TransformTypeInt tar = new TransformTypeInt(); tar.SourceInt = source; return tar; } /// <summary> /// 重写+操作符,实现两个值追加,注意这里的static,public operator /// </summary> /// <param name="var1"></param> /// <param name="var2"></param> /// <returns></returns> public static TransformTypeInt operator +(TransformTypeInt var1,TransformTypeInt var2) { TransformTypeInt tar = new TransformTypeInt(); string a = var1.SourceInt.ToString() + var2.SourceInt.ToString(); tar.SourceInt = Convert.ToInt32(a); return tar; } } /// <summary> /// 显式转换 /// </summary> class ExplicitTrans { string sourceStr; public string SourceStr { set { sourceStr = value; } get { return sourceStr; } } public static explicit operator string(ExplicitTrans source) { return source.SourceStr; } public static explicit operator ExplicitTrans(string source) { ExplicitTrans tar = new ExplicitTrans(); tar.SourceStr = source; return tar; } } } 程序的执行结果附上一张经典的控制台截图(^-^)V
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论