C#中的类的“引用字段”和“非引用字段”

C#中,相似的写法,只是类的字段类型,一个是 int型,一个是自定义的简单封装了一个int字段的类类型,其它代码都一样,但是结果却是相差巨大,一个被编译器认为是引用字段,一个被编译器认为是普通数值字段。这是为什么呢?

代码如下:


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


//下面是代码1
namespace super                                         //这样,test类中的mix字段会被编译器认为是引用字段
{
    public class myint
    {
        public int myix;
    }
    public class test                   //这样也是可以实现引用字段的,前提好像就是一定要在某个地方调用下非默认的构造函数
    {
        public myint mix = new myint();                //这里是对一个临时int对象的引用吗,这个临时的对象虽然不知道名字,但是一直存在,且位于堆上 
        public object GetCopy()
        {
            return MemberwiseClone();                //这里来了一个浅拷贝
        }
    }
}
namespace classpractise2
{
    class Program
    {
        static void Main(string[] args)
        {
            test s1 = new test();                //②
            test s2 = (test)s1.GetCopy();
            Console.WriteLine(s2.mix.myix);
            s1.mix.myix = 5;
            Console.WriteLine(s2.mix.myix);
        }
    }
}


//下面是代码2
namespace super               //这样,test类中的mix字段不会被编译器认为是“引用字段”
{
    public class test                   //这样也是可以实现引用字段的,前提好像就是一定要在某个地方调用下非默认的构造函数
    {
        public int mix = new int();                //这里是对一个临时int对象的引用吗,这个临时的对象虽然不知道名字,但是一直存在,且位于堆上 
        public object GetCopy()
        {
            return MemberwiseClone();                //这里来了一个浅拷贝
        }
    }
}
namespace classpractise2
{
    class Program
    {
        static void Main(string[] args)
        {
            test s1 = new test();                //②
            test s2 = (test)s1.GetCopy();
            Console.WriteLine(s2.mix);
            s1.mix = 5;
            Console.WriteLine(s2.mix);
            Console.WriteLine(s1.mix);
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值