C#中的自定义类型转换

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. //用户自定义转换
  5. //所有的用户自定义转换都是静态的,要使用static关键字
  6. //用户自定义转换分显示和隐示,它们用implicit(隐式转换)或 explicit(显示转换)关键字声明。
  7. //static 访问修辞符 转换修辞符 operator 转换类型(参数)
  8. namespace CountStrDemo
  9. {
  10.     class 自定义类型转换
  11.     {
  12.         //public static void Main(string[] args)
  13.         //{
  14.         //    MyCaseDemo obj = new MyCaseDemo( 5 , 8 );
  15.         //    //隐式转换
  16.         //    float f = obj;
  17.         //    Console.WriteLine( f.ToString() );
  18.         //    //显式转换
  19.         //    int i = (int)obj;
  20.         //    Console.WriteLine( i.ToString() );
  21.         //    Console.Read();
  22.         //}
  23.         class MyCaseDemo
  24.         {
  25.             public int x;
  26.             public int y;
  27.             public MyCaseDemo(int x, int y)
  28.             {
  29.                 this.x = x;
  30.                 this.y = y;
  31.             }
  32.             // 与运算重载差区别, operator后跟着的是要转成的类型,不是符号.同时也是本方法的返回类型  
  33.             //还及是必须用implicit(隐式转换)或 explicit(显示转换)关键字声明。
  34.             public static implicit operator float(MyCaseDemo obj)
  35.             {
  36.                 return obj.y * obj.x;  
  37.             }
  38.             public static explicit operator int ( MyCaseDemo obj )
  39.             {
  40.                 return obj.y + obj.x;
  41.             }
  42.         }
  43.     }
  44. }
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Text;
    4. namespace CountStrDemo
    5. {
    6.     class 类与类的自定义转换
    7.     {
    8.         public static void Main(string[] args)
    9.         {
    10.             C c = new C();
    11.             D d = c;
    12.             Console.WriteLine( d.name );
    13.             Console.Read();
    14.         }
    15.     }
    16.     class B
    17.     { 
    18.     }
    19.     class C : B
    20.     {
    21.         public string name = "c name";
    22.         public static implicit operator D(C c)
    23.         { 
    24.             D d = new D() ;
    25.             d.name = c.name + "让人给搞了";
    26.             return d;
    27.         }
    28.     }
    29.     class D : B
    30.     {
    31.         public string name = "d name";
    32.     }
    33. }
    34. // 类与类之前的转换,不能转换两个直接或者简介继承的关系的类,
    35. //在上例中 C->B D-B都是不对的,唯一的关系只有C->D或者D-C,但是,不可以在CD两类中都定义转换,否则会让编译器搞不清
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值