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);
}
}
}