引用类型,值类型,装箱拆箱

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 引用类型
{
    class Program
    {
        class DataTypeTest
        {
            public int Val;
        }
        static void Main(string[] args)
        {
            DataTypeTest objTest = new DataTypeTest();
            objTest.Val = 100;
            Console.WriteLine("变量的值为  {0}", objTest.Val);
            // 传递属于引用类型的对象
            Test(objTest);
            // 由于该数据类型属于引用类型,所以会考虑新处理的值 
            Console.WriteLine("变量的值为  {0}", objTest.Val);

            //程序等待
            Console.ReadLine();
        }
        static void Test(DataTypeTest dataTest)
        {
            int temp = 10;
            dataTest.Val = temp * 20;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 值类型
{
    class Program
    {
        static void Main(string[] args)
        {
            // 声明一个值类型的整型数据类型
            int val = 100;
            Console.WriteLine("该变量的初始值为  {0}", val);
            Test(val);
            // 由于该数据类型属于值类型,所以将恢复其初始值  
            Console.WriteLine("该变量的值此时为  {0}", val);

            //程序等待
            Console.ReadLine();
        }
        static void Test(int getVal)
        {
            int temp = 10;
            getVal = temp * 20;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 装箱和拆箱
{
    class Program
    {
        static void Main(string[] args)
        {  
            //值类型转换为引用类型--装箱
                //引用类型再转换为值类型--装箱和拆箱
                    //只有装箱过的对象才能被拆箱
            int a = 122;
            string s = a.ToString();//装箱
            string s1 = "123";
            int i = int.Parse(s1);//拆箱
         //实现值类型和引用类型的转换

            int i1 = 100;
            Object oj = i1;//隐式的装箱
            Console.WriteLine("值为:{0}",oj);
            int i2 =(int)oj;//显式的拆箱
            Console.WriteLine(i2);

            //程序等待
            Console.ReadLine();
        }
    }
}

 

posted @ 2024-04-09 20:12  困到很想醒  阅读(4)  评论(0编辑  收藏  举报