通過implicit 和運(yùn)算符重載想到一種坑爹的寫法,專門對付強(qiáng)制==ture,或者強(qiáng)制不能帶==true的。
我在這個(gè)帖子System.Convert 的一些事 的一個(gè)關(guān)于代碼風(fēng)格留言,發(fā)現(xiàn)還是有些爭論的,我就想有沒有辦法讓if (obj) 和 if (obj == ture)的行為不一樣呢?我實(shí)驗(yàn)了一下,果然可以。
比如下面的代碼
1 static void Main(string[] args)
2 {
3 var confusedValue = GetValue();
4
5 if (confusedValue == true)
6 {
7 Console.WriteLine("confusedObj == true");
8 }
9
10 if (confusedValue)
11 {
12 Console.WriteLine("隱式轉(zhuǎn)換 confusedObj == true");
13 }
14
15 if (!confusedValue)
16 {
17 Console.WriteLine("隱式轉(zhuǎn)換 confusedObj == false");
18 }
19 }
直覺上,一定認(rèn)為 if (confusedValue == true) 和 if (confusedValue) 是一樣的,其實(shí)不然,實(shí)際運(yùn)行的結(jié)果是:

這種效果是這樣實(shí)現(xiàn)滴
1 public class ConfusedClass
2 {
3 public static bool operator == (ConfusedClass left, bool right)
4 {
5 return right;
6 }
7
8 public static bool operator !=(ConfusedClass left, bool right)
9 {
10 return !right;
11 }
12
13 public static implicit operator bool(ConfusedClass obj)
14 {
15 return false;
16 }
17
18 public override bool Equals(object obj)
19 {
20 return base.Equals(obj);
21 }
22 }
我簡單的解釋一下這個(gè)類,首先我重載了運(yùn)算符==和!=,這樣在confusedValue == true的時(shí)候,其實(shí)是執(zhí)行了第四3行~6行的函數(shù)。
然后,我又用了implicit關(guān)鍵字,implicit關(guān)鍵字用于聲明隱式的用戶定義類型轉(zhuǎn)換運(yùn)算符,這樣,當(dāng)ConfusedClass的實(shí)例隱身轉(zhuǎn)換為bool的時(shí)候,無論如何都返回false了。
如果想要搗亂的話,這樣倒是一種方法。比如原來if (confusedValue)是正常的,但是你的項(xiàng)目經(jīng)理規(guī)定了代碼風(fēng)格必須是if (confusedValue == true)的,你就可以設(shè)置一個(gè)陷阱,如果別人把你的代碼或用你的類的時(shí)候用了if (confusedValue == true)的寫法,就是相反的。反之亦然。
最后,我不鼓勵(lì)搗亂的哈,如果然讓我rewiew代碼,碰到坑爹類型隱式轉(zhuǎn)換,肯定要求刪掉,不過implicit關(guān)鍵字的確是很少見啦。

浙公網(wǎng)安備 33010602011771號(hào)