今天向朋友请教一个问题,对话是这样子的,
问:c#下用一个实例 赋给一个新定义的对象,是copy过去?还是引用?
答:引用
问:你肯定?
答: 恩,C#下的赋值都是引用
完了我就写了下面的代码去测试,代码如下:
class myClass
{
public int num ;
};
struct myStruct
{
public int num ;
};
class Program
{
static void Main(string[] args)
{
myClass myclass = new myClass();
myClass myclassb = myclass;
myClass myclassa = new myClass();
myclassa = myclass;
myclassa.num = 1;
Console.WriteLine("myclass.num = " + myclass.num.ToString());
Console.WriteLine("myclassa.num =" + myclassa.num.ToString() + "\t\tmyclassb.num = " + myclassb.num.ToString());
myclass.num = 2;
Console.WriteLine("myclass.num = " + myclass.num.ToString());
Console.WriteLine("myclassa.num =" + myclassa.num.ToString() + "\t\tmyclassb.num = " + myclassb.num.ToString());
/////////////////////////////////////////////////////////////////////
myStruct mystruct = new myStruct();
myStruct mystruct1 = mystruct;
mystruct1.num = 1;
Console.WriteLine("\n\nmystruct.num =" + mystruct.num.ToString() + "\t\tmystruct1.num =" + mystruct1.num.ToString());
mystruct.num = 2;
Console.WriteLine("mystruct.num =" + mystruct.num.ToString() + "\t\tmystruct1.num =" + mystruct1.num.ToString());
}
}
{
public int num ;
};
struct myStruct
{
public int num ;
};
class Program
{
static void Main(string[] args)
{
myClass myclass = new myClass();
myClass myclassb = myclass;
myClass myclassa = new myClass();
myclassa = myclass;
myclassa.num = 1;
Console.WriteLine("myclass.num = " + myclass.num.ToString());
Console.WriteLine("myclassa.num =" + myclassa.num.ToString() + "\t\tmyclassb.num = " + myclassb.num.ToString());
myclass.num = 2;
Console.WriteLine("myclass.num = " + myclass.num.ToString());
Console.WriteLine("myclassa.num =" + myclassa.num.ToString() + "\t\tmyclassb.num = " + myclassb.num.ToString());
/////////////////////////////////////////////////////////////////////
myStruct mystruct = new myStruct();
myStruct mystruct1 = mystruct;
mystruct1.num = 1;
Console.WriteLine("\n\nmystruct.num =" + mystruct.num.ToString() + "\t\tmystruct1.num =" + mystruct1.num.ToString());
mystruct.num = 2;
Console.WriteLine("mystruct.num =" + mystruct.num.ToString() + "\t\tmystruct1.num =" + mystruct1.num.ToString());
}
}
代码看完了,写出你认为的结果,是什么?
我想不用说大家都知道结论是什么了吧 *^_^*