C#一元运算重载的深入理解
生活随笔
收集整理的這篇文章主要介紹了
C#一元运算重载的深入理解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C#一元運算重載的深入理解
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;//類型轉換只能是public static implicit形式或public static explicit形式//,這里的implicit與explicit并不是返回值類型,而是修飾符,說明是隱式轉換還是顯式轉換//因此不能寫成public static bool operator bool(CDT odt)這樣的形式,編譯會出錯//應用場景 //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;}//應用場景://CDT ot = new CDT(); string s = (string) otpublic static explicit operator string(CDT odt){Console.WriteLine("operator string------------------");return odt.ToString();}//應用場景://CDT ot = new CDT(); string s = otpublic static implicit operator int(CDT odt){Console.WriteLine("operator string------------------");return odt.x;}//重載 true false運算符(注意的MSDN文檔說明中說true和false是運算符,就像 +,-普通運算符一樣)//兩者必須一起重載。其實就相當于重載一個bool運算符的效果, 并不完全等價//應用場景://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)//編譯錯誤:CDTX的訪問權限不能小于TestLimitX的訪問權限//{//}public static void TestLimit(CDT ot)//可以訪問 {if (ot) { }//調用operator turebool b = ot;//調用operator bool,若無此重載,則編譯錯誤,并不會調用operator ture 或ooperator falsestring st = (string)ot; //可以轉換,調用重載的顯示的string轉換運算符CDTX otx = new CDTX();//string stx = (string)otx; //編譯出錯,不能轉換 Console.WriteLine(b);}static void Main(string[] args){TestLimit(new CDT(112));}}?
posted on 2016-11-12 14:42 時空觀察者9號 閱讀(...) 評論(...) 編輯 收藏
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的C#一元运算重载的深入理解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LINQ 查询表达式(C# 编程指南)
- 下一篇: c# char unsigned_dll