C#运算符重载实例是学习C#运算符重载的重要途径。让我们来看看下面的C#运算符重载实例吧:
- using System;
- class hello
- ...{//逻辑运算符 & | ! 按位运算
- static void Main()
- ...{//rectangle长方形[rek tan gl]
- string sName;int sInt;
- Console.Write("Input Name:"); sName=Console.ReadLine();
- Console.Write("Input a Number:"); sInt = int.Parse(Console.ReadLine());
- clsString myStr=new clsString();
- myStr.sL = sName; myStr++;//利用C#运算符重载之重载的++运算符使其转变为大写
- clsNot myNotStr = new clsNot();
- myNotStr.sL = sName; myNotStr=!myNotStr;//利用C#运算符重载之重载的++运算符使其转变为大写
- Console.WriteLine("The Enter Number is: {0}", sInt);
- clsInt myInt = new clsInt();
- myInt.sL = sInt; myInt++;
- object ob = myInt.sL;//装箱
- AdverseCase mStr = new AdverseCase(); mStr.sL = sName;//利用类的全局变量转换
- string c = myStr;
- Console.WriteLine("Upper Name is: {0}", c);//隐含转换成字符串
- Console.WriteLine("Your Name is: {0}", sName);
- Console.WriteLine("Not Name is: {0}", myNotStr.sL);
- Console.WriteLine("Cls Name is: {0}", mStr.ToAdverseCase());
- Console.WriteLine("The Number Increase is: {0}", ob);
- Console.ReadLine();
- }
- }
- class clsString//C#运算符重载之重载++运算符使字符串变大写
- //如果要重载++运算符使其能直接用于string怎么处理
- ...{
- public string sL;
- public static clsString operator ++(clsString strIn)
- ...{
- clsString cs = new clsString();
- cs.sL = strIn.sL.ToUpper();
- return cs;
- }
- //隐含转换public static implicit operator string(clsString c)
- //明确转换public static explicit operator string(clsString c)
- //重载 类型转换 由clsString转换为 string
- public static implicit operator string(clsString c)
- ...{
- string i; i = c.sL;
- return i;
- }
- }
- class clsInt//C#运算符重载之重载++运算符使整形数据每次增加10
- ...{
- public int sL;
- public static clsInt operator ++(clsInt strIn)
- ...{
- clsInt ci = new clsInt();
- ci.sL = strIn.sL+10;
- return ci;
- }
- }
- class clsNot//利用C#运算符重载之运算符 ! 重载转换翻转字符串大小写
- ...{
- public string sL;
- public static clsNot operator !(clsNot strIn)
- ...{
- clsNot ci = new clsNot();
- ci.sL = RevServer(strIn.sL);
- return ci;
- }
- protected static string RevServer(string s)
- ...{//大写变小写,小写变大写
- char[] ct;
- if (s.Length == 1)
- ...{
- ct = s.ToCharArray();
- if (ct[0] >= 'a')s = s.ToUpper();else s = s.ToLower();
- return s;
- }
- string sTmp = s.Substring(0, 1);
- ct = sTmp.ToCharArray();
- if (ct[0] >= 'a')
- sTmp = sTmp.ToUpper();
- else
- sTmp = sTmp.ToLower();
- sTmp += RevServer(s.Substring(1));
- return sTmp;
- }
- }
- //利用类成员转换翻转字符串大小写
- class AdverseCase
- ...{
- public string sL;
- public string ToAdverseCase()
- ...{
- return RevServer(this.sL);
- }
- protected static string RevServer(string s)
- ...{//大写变小写,小写变大写
- char[] ct;
- if (s.Length == 1)
- ...{
- ct = s.ToCharArray();
- if (ct[0] >= 'a') s = s.ToUpper(); else s = s.ToLower();
- return s;
- }
- string sTmp = s.Substring(0, 1);
- ct = sTmp.ToCharArray();
- if (ct[0] >= 'a')
- sTmp = sTmp.ToUpper();
- else
- sTmp = sTmp.ToLower();
- sTmp += RevServer(s.Substring(1));
- return sTmp;
- }
- }
C#运算符重载实例的内容就向你介绍到这里,希望对你学习C#运算符重载有所帮助。
【编辑推荐】