C#基础:自定义显式转换和隐式转换

显式转换和隐式转换不仅可以用在数学运算符,还可以自定义类型之间的显式转换和隐式转换。

示例代码如下:

       //自定义 隐式转换,显示转换

  1.   public class ConvClass1 {//类型1:隐式转换关键字implicit
  2.         public int val; //int类型    operator运算符关键字
  3.         public static implicit operator ConvClass2(ConvClass1 op1) {
  4.             ConvClass2 con = new ConvClass2();
  5.             con.val = op1.val;//隐式转换 关键字implicit
  6.             return con;
  7.         }
  8.     }
  9.  public class ConvClass2 {//类型2:显式转换关键字explicit
  10.         public double val;//double类型
  11.         public static explicit operator ConvClass1(ConvClass2 op2) {
  12.             ConvClass1 con = new ConvClass1();
  13.             checked{ con.val = (int)op2.val; }//显式转换  关键字explicit
  14.             return con;
  15.         }
  16.     }
  17.  public class Pargram{
  18.        public stitic void Main(string[] args){
  19.             ConvClass1 op1 = new ConvClass1();
  20.             op1.val = 6;
  21.             ConvClass2 op2 = op1;//隐式转换
  22.             ConvClass2 op3 = (ConvClass2)op1;//显式转换
  23.             Console.WriteLine(op1.val);
  24.             Console.WriteLine(op2.val);
  25.             Console.WriteLine(op3.val);
  26.       }
  27. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值