C#之自己定义的implicit和explicit转换

C#之自己定义的implicit和explicit转换

大家好,又见面了,我是全栈君,祝每个程序员都可以多学几门语言。

在类型转换时常会遇到隐式转换和显式转换。那我们自己定义的类型要怎样去定义隐式转换和显式转换?我们来看一段代码

public class Rational
    {
        private Int32 _inner_int = 0;

        public Rational()
        {

        }

        public Rational(Int32 num)
        {
            this._inner_int = num;
        }


        public Int32 ToInt32() { return this._inner_int; }

        // Implicitly constructs and returns a Rational from an Int32 
        public static implicit operator Rational(Int32 num)
        {
            return new Rational(num);
        }

        // Explicitly returns an Int32 from a Rational 
        public static explicit operator Int32(Rational r)
        {
            return r.ToInt32();
        }

        public override string ToString()
        {
            //return base.ToString();
            String s = String.Format("{0}", this._inner_int);
            return s;
        }
    }

測试代码

  class Program
    {
        static void Main(string[] args)
        {
            Rational r1 = 10;          
            Console.WriteLine(r1);       

            Int32 i = r1;     
            Console.WriteLine(i);       
            Console.ReadLine();
        }
    }

这时编辑会报错,见下图

C#之自己定义的implicit和explicit转换

从提示能够看到,是由于Int32 i=r1时缺少了显式转换。如今我们加入显示转换,改动后的代码及输出结果例如以下:
C#之自己定义的implicit和explicit转换

结果正常输出为10.

那为什么会这样呢?究其原因是在Rational转换成 Int32时,指定了explicit(显式的),所以必需要指定转换类型Int32。假设将explicit换成implicit(隐式),原来的代码将能够正常执行。

改动后的Rational

 public class Rational
    {
        private Int32 _inner_int = 0;

        public Rational()
        {

        }

        public Rational(Int32 num)
        {
            this._inner_int = num;
        }


        public Int32 ToInt32() { return this._inner_int; }

        // Implicitly constructs and returns a Rational from an Int32 
        public static implicit operator Rational(Int32 num)
        {
            return new Rational(num);
        }

        // Explicitly returns an Int32 from a Rational 
        public static <span style="color:#ff0000;">implicit</span> operator Int32(Rational r)
        {
            return r.ToInt32();
        }

        public override string ToString()
        {
            //return base.ToString();
            String s = String.Format("{0}", this._inner_int);
            return s;
        }
    }

測试代码及输出结果

C#之自己定义的implicit和explicit转换

可见explicit和implicit影响着类型的显式转换和隐式转换。

事实上在Rational r1=10已经运行了隐式转换,相应的转换代码例如以下:

 // Implicitly constructs and returns a Rational from an Int32 
        public static implicit operator Rational(Int32 num)
        {
            return new Rational(num);
        }

假设将implicit换成explicit,Rational r1=10也将会报错(能够自行測试)。

转载请注明出处:http://blog.csdn.net/xxdddail/article/details/38057563

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/118136.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • MySQL索引的创建与使用

    MySQL索引的创建与使用索引有很多,且按不同的分类方式,又有很多种分类。不同的数据库,对索引的支持情况也不尽相同。声明:本人主要简单示例MySQL中的单列索引、组合索引的创建与使用。索引的创建:建表时创建:CREATETABLE表名(字段名数据类型[完整性约束条件],……,[UNIQUE|FULLTEXT|SPATIAL]INDEX|KEY[索引名](字…

    2022年5月30日
    36
  • pandas处理缺失值的函数_pandas填充缺失值

    pandas处理缺失值的函数_pandas填充缺失值df.dropna()函数用于删除dataframe数据中的缺失数据,即删除NaN数据.官方函数说明:DataFrame.dropna(axis=0,how=’any’,thresh=None,subset=None,inplace=False) Removemissingvalues. SeetheUserGuideformoreonwhichvaluesareconsideredmissing, andhowtoworkwithmissing

    2022年9月17日
    0
  • 深入理解CMA【转】

    深入理解CMA【转】

    2021年6月11日
    101
  • Postman安装教程_postman需要联网吗

    Postman安装教程_postman需要联网吗1.官网安装(别看)打开官网,https://www.getpostman.com安装很麻烦还很容易安装失败(先请擦掉眼泪,不要忧伤,我们依然可以好好的)2.非官网安装这是一种直接通过打包已经安装的扩展程序的方式,来进行我认为的「非法安装」,但没办法,只能这样。我会给你一个安装包,见附件。你应该下载下来,解压缩到你喜欢的位置。(解压的位置自己要记得)安装包(Postman4.1.2下载地址:http://files.cnblogs.com/files/mafly/postman-4

    2022年9月17日
    0
  • 深信服SCSA安全工程师题库(方便大家复习备考)

    深信服SCSA安全工程师题库(方便大家复习备考)1、【EDR】下列哪个端口是紧急情况下EDR管理平台和客户端通信端口,即紧急情况下用于下发Agent重启、Agent卸载和Agent停止等指令。()A:443.0B:54120.0C:8083.0D:8088.0正确答案B2、【EDR】客户有7000个终端需要安装EDR客户端进行安全防护,请问推荐部署多少个EDR管理平台()A:1个B:2个C:4个D:6个正确答案C3、【EDR】EDR的Agent客户端不支持在以下哪种类型的终端上安装()A:WindowsServerB

    2022年6月20日
    45
  • 百度地图API显示多个标注点带百度样式信息检索窗口的代码

    百度地图API显示多个标注点带百度样式信息检索窗口的代码

    2021年10月10日
    36

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号