C#一元运算重载的深入理解
生活随笔
收集整理的這篇文章主要介紹了
C#一元运算重载的深入理解
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
C#一元運(yùn)算重載的深入理解
using System; using System.Diagnostics; using System.Text; using System.Collections; using System.Collections.Generic; delegate string DTE(int x, string s);class MYTestX {public class CDT{public CDT(int x){this.x = x;}int x = 10;//類型轉(zhuǎn)換只能是public static implicit形式或public static explicit形式//,這里的implicit與explicit并不是返回值類型,而是修飾符,說明是隱式轉(zhuǎn)換還是顯式轉(zhuǎn)換//因此不能寫成public static bool operator bool(CDT odt)這樣的形式,編譯會(huì)出錯(cuò)//應(yīng)用場(chǎng)景 //1: CDT ot = new CDT(); if(ot){}//2: CDT ot = new CDT(); bool b = ot;public static implicit operator bool(CDT odt){Console.WriteLine("operator bool------------------");return odt != null;}//應(yīng)用場(chǎng)景://CDT ot = new CDT(); string s = (string) otpublic static explicit operator string(CDT odt){Console.WriteLine("operator string------------------");return odt.ToString();}//應(yīng)用場(chǎng)景://CDT ot = new CDT(); string s = otpublic static implicit operator int(CDT odt){Console.WriteLine("operator string------------------");return odt.x;}//重載 true false運(yùn)算符(注意的MSDN文檔說明中說true和false是運(yùn)算符,就像 +,-普通運(yùn)算符一樣)//兩者必須一起重載。其實(shí)就相當(dāng)于重載一個(gè)bool運(yùn)算符的效果, 并不完全等價(jià)//應(yīng)用場(chǎng)景://CDT ot = new CDT(); if(ot){}//不能用于: CDT ot = new CDT(); bool b = ot; bool b2 = (bool)ot;public static bool operator true(CDT odt){return odt != null;}public static bool operator false(CDT odt){return odt == null;}}class CDTX { }//public void TestLimitX(CDTX ot)//編譯錯(cuò)誤:CDTX的訪問權(quán)限不能小于TestLimitX的訪問權(quán)限//{//}public static void TestLimit(CDT ot)//可以訪問 {if (ot) { }//調(diào)用operator turebool b = ot;//調(diào)用operator bool,若無此重載,則編譯錯(cuò)誤,并不會(huì)調(diào)用operator ture 或ooperator falsestring st = (string)ot; //可以轉(zhuǎn)換,調(diào)用重載的顯示的string轉(zhuǎn)換運(yùn)算符CDTX otx = new CDTX();//string stx = (string)otx; //編譯出錯(cuò),不能轉(zhuǎn)換 Console.WriteLine(b);}static void Main(string[] args){TestLimit(new CDT(112));}}?
posted on 2016-11-12 14:42 時(shí)空觀察者9號(hào) 閱讀(...) 評(píng)論(...) 編輯 收藏
與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的C#一元运算重载的深入理解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LINQ 查询表达式(C# 编程指南)
- 下一篇: U3D sorting layer, s