C# implicit和explicit

今天在学可空类型的时候,看见两个关键字——implicit和explicit。

        public static implicit operator T? (T value);
        public static explicit operator T(T? value);

这两个关键字是一对用于类型转换的关键字。

 

1、implic意味着可隐式转换,让转换可以隐式进行也可显式进行,例子如下。

    public class NInt
    {
        private int value;

        public static implicit operator NInt(int i)
        {
            NInt nInt = new NInt
            {
                value = i
            };
            return nInt;
        }
    }
  NInt nInt2 = (NInt)1;;//正确
  NInt nInt = 1;//正确

 

2、explicit意味着必须显式进行转换,例子如下:

    public class NInt
    {
        private int value;

        public static explicit operator NInt(int i)
        {
            NInt nInt = new NInt
            {
                value = i
            };
            return nInt;
        }
    }

    NInt nInt1 = 1;//错误
    NInt nInt2 = (NInt)1;//正确

 

posted @ 2021-10-28 19:04  mshentai  阅读(74)  评论(0编辑  收藏  举报