In this post, system. there is still some debate about the code style message about convert. I wonder if I can make the behavior of IF (OBJ) And if (OBJ = ture) Different? I tried it.
For example, the following code
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 ("implicit conversion confusedobj = true ");
13}
14
15 if (! Confusedvalue)
16 {
17 console. writeline ("implicit conversion confusedobj = false ");
18}
19}
Intuitively, we must think that if (confusedvalue = true) And if (confusedvalue) are the same. Otherwise, the actual running result is as follows:
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 }
I briefly explained this class. First, I overloaded the operators = and! =, So when confusedvalue = true, the fourth line is actually executed ~ Six rows of functions. Then, I used the implicit keyword, which is used to declare an implicit user-defined type conversion operator. In this way, when the confusedclass instance is implicitly converted to bool, in any case, false is returned.
If you want to make trouble, This is a method. For example, if (confusedvalue) is normal, but your project manager specifies that the Code style must be if (confusedvalue = true), you can set a trap, if someone else uses the IF (confusedvalue = true) method to write your code or use your class, the opposite is true. And vice versa.
Finally, I don't want to be confused. For example, if I had the Rewiew code and encountered implicit type conversion, I must delete it. However, implicit keywords are rare.