借用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/

FileDownload.aspx?ProjectName=1code&DownloadId=165659&Build=17601

PS:我的同事开发了一个MSDN论坛的小工具,有兴趣的朋友可以试试,此工具已开始在国内推行:

MSDN论坛好帮手

转载于:https://www.cnblogs.com/telnet_mike/archive/2011/01/23/create_MyBool_data_type_by_implicit.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值