此idea是由我处理一个帖子的时候突然蹦出来的,感觉可能有的朋友需要,就将我的回复帖在我的blog,由于时间问题,我没有写中文版的,而是直接用的英文,希望大家见谅,不过代码会告诉大家我的思路,其实也没多少可以解释的,我认为这只是一个小技巧罢了。
I use the Implicit Conversion Operator to help us do the similar things as we inherit from the Boolean type, but MyBool type is not a Boolean type.
And then we can override some methods like Equal method, ToString method and so on.
class TestProgram { static void Main(string[] args) { MyBool mb = true; mb.PrintMessage("hello MyBool DataType!"); Console.WriteLine(mb.ToString()); Console.ReadLine(); } } public class MyBool { private bool myBool; public MyBool() { } public MyBool(bool b) { myBool = b; } // implicit bool to MyBool conversion operator public static implicit operator MyBool(bool b) { return new MyBool(b); // implicit conversion } // implicit MyBool to bool conversion operator public static implicit operator bool(MyBool mb) { return mb.myBool; // implicit conversion } public void PrintMessage(string msg) { Console.WriteLine(msg); } public string ToString() { return myBool.ToString(); } }
大家有兴趣的话,可以点击下面的链接进入论坛原帖:
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/a7ca771d-394d-4a5a-b1f7-4c6729cf50cd/
PS:我的同事开发了一个MSDN论坛的小工具,有兴趣的朋友可以试试,此工具已开始在国内推行: