zoukankan      html  css  js  c++  java
  • c# 类型转换符的重载

     1 本例开始,定义一个personx 类,怎么实现
     2  personx p=new personx();
     3  int age=p;
     4  或者
     5  p=100;
     6 
     7 这是把personx实例直接赋值给整形,或者反之,把一个引用类型赋值给值类型,正常编译器会直接报错,不允许通过编译的,但是C#的类型重载却可以为我们提供一种实现。
     8 
     9 class Personx:Top
    10     {
    11         public Personx():base(4)
    12         {
    13             
    14         }
    15        //int  -> Personx
    16         public static implicit operator Personx(int x)
    17         {
    18             var tmp = new Personx();
    19             tmp.x = x;
    20             return tmp;
    21         }
    22       //Personx -> int
    23         public static implicit operator Int32(Personx per)
    24         {
    25             return per.x;
    26         }
    27 
    28     }
    29 
    30 abstract class Top
    31     {
    32         public int x;
    33         public string name;
    34         public Top() { }
    35         protected Top(int x)
    36         {
    37             this.x = x;
    38         }        
    39     }
    40     
    41 
    42 
    43 注:
    44 上述的两个类型转换方法即可实现我们的需求,当然必须是public  static 修饰,要注明 是需要隐式转换还是显式转换, implicitexplicit
    45 
    46 修饰不一样,使用起来也不一样,应用:
    47
    当然,如果不是有特殊需求,一般建议还是少用这种类型转换,这种类型转换带来了更多拓展性,但是同时也带来一些危险性,在不细心的情况下很容易对引用类型进行修改,然后自己也不清楚,编译器也不提醒
    48 隐式转换
    49  Personx tmp =9;
    50  System.Diagnostics.Debug.WriteLine(tmp.x);
    51 
    52 显示转换
    53  Personx tmp=(Personx)9;
  • 相关阅读:
    SpringBoot 集成Log4j、集成AOP
    SpringBoot 集成JUnit
    SpringBoot yml文件语法
    SpringBoot 集成MyBatis、事务管理
    SpringBoot 集成Spring JDBC
    模板引擎简介
    SpringBoot 解决“不支持发行版本xx”的问题
    SpringBoot 全局异常处理
    SpringBoot 静态资源的配置
    SpringBoot的起步依赖
  • 原文地址:https://www.cnblogs.com/yeshuimaowei/p/7119474.html
Copyright © 2011-2022 走看看