using System; public struct DBBool { ? public static readonly True = new DBBool(1); ? public static readonly False = new DBBool(-1); ? public static readonly Null = new DBBool(0); ? private sbyte value; ? private DBBool(int val) { value = val; } ? public static implicit operator DBBool(bool x) ? { ? ? ? return x ? True : False; ? } ? public static explicit operator bool(DBBool x) ? { ? ? ? return x.value > 0; ? } ? public static DBBool operator &(DBBool x , DBBool y) ? { ? ? ? return new DBBool(//...); ? } ? public static DBBool operator |(DBBool x , DBBool y) ? { ? ? ? return new DBBool(//...); ? } ? public static bool operator true(DBBool x) ? { ? ? ? return x.value > 0; ? } ? public static bool operator false(DBBool x) ? { ? ? ? return x.value < 0; //這里出現(xiàn)了問題 ? } ? ? public static DBBool operator !(DBBool x) ? ? { ? ? ? return new DBBool(-x.value); ? ? } } public class Test { ? static void Main() ? ? { ? ? ? DBBool blTrue = true; ? ? ? DBBool blFalse = false; ? ? ? if(blTrue) //(1) ? ? ? ? Console.WriteLine("OK"); //可以執(zhí)行. ? ? ? if(blFalse) //(2) ? ? ? ? Console.WriteLine("OK");? //為什么這里不能執(zhí)行? ? ? ? if(!blFalse) //(3) ? ? ? ? Console.WriteLine("OK"); //可以執(zhí)行. ? ? } } (2)在進行if判斷時,本來在底層的false運算符內(nèi)部原以為可以返回true呢? 但是從實際測試后角度出發(fā),預(yù)期效果感覺不是按照定義的那樣執(zhí)行結(jié)果! 由于重載了運算符"!",從(3)if判斷中又可以正常執(zhí)行,所以使我更加糊涂了! ? 在(2)中重載的false運算符執(zhí)行了嗎?那么為什么不能返回true呀? ? 請詳細(xì)回答!!!!!!!
2 回答

翻翻過去那場雪
TA貢獻2065條經(jīng)驗 獲得超14個贊
根據(jù)C#語言規(guī)范7.20節(jié)的描述:對于需要布爾表達式的語句,如if、while、do、for等,都需要布爾表達式的類型重載explicit bool或operator true。也就是說對于這些語句,所執(zhí)行的都是operator true的重載,因此LZ的(2)執(zhí)行的是operator true,沒有執(zhí)行operator false。
那么operator false什么時候執(zhí)行呢?在執(zhí)行&&操作時,會首先調(diào)用operator false來判斷是否為false,若是則直接跳出;在執(zhí)行||操作時,會首先調(diào)用operator true來判斷是否為true,若是則直接繼續(xù)執(zhí)行。LZ可以通過調(diào)試來驗證這些結(jié)論。
此外,operator true和operator false必須成對出現(xiàn)。
- 2 回答
- 0 關(guān)注
- 367 瀏覽
添加回答
舉報
0/150
提交
取消