qq_42889230
秋朔风华
2018-11-07 13:38

c# System.NullReferenceException:“Object reference not set to an instance of an object.”

  • c#

不知道为什么出现异常
图片说明

 using System;

namespace _12._1._3可空类型的装箱拆箱
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("可空的类型的装箱拆箱如下:");
            BoxdandUnboxed();
            Console.Read();
        }

        public static void BoxdandUnboxed()
        {
            Nullable<int> nullable = 5;
            int? nullablewithoutvale = null;
            Console.WriteLine("获取不为null的可空类型为{0}",nullable.GetType());
            Console.WriteLine("获取为null的可空类型为:{0}", nullablewithoutvale.GetType());
            object obj = nullable;

            Console.WriteLine("装箱后obj的类型为{0}",obj.GetType());

            int value = (int)obj;
            Console.WriteLine("拆箱后非可空变量的情况为{0}",value);

            nullable = (int?)obj;
            Console.WriteLine("拆箱后可空变量的情况为{0}",nullable);

            obj = nullablewithoutvale;
            Console.WriteLine("对null的可空类型装箱后obj是否为null:{0}",obj==null);

            nullable = (int?)obj;
            Console.WriteLine("一个没有值的可空类型装箱后,拆成可空变量是否为null:{0}",nullable==null);

        }
    }
}

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答