借用implicit创建我们自己的布尔数据类型-create MyBool data type by implicit

此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论坛的小工具,有兴趣的朋友可以试试,此工具已开始在国内推行:

MSDN论坛好帮手

posted @ 2011-01-23 22:53  Mike Dos Zhang  阅读(1165)  评论(0编辑  收藏  举报