C#中结构Struct定义的变量是引用类型的吗?
using System;
class MyType
{
private string name;
public string Name
{
set
{
name=value;
}
get
{
return name;
}
}
}
class AppType
{
public static void Main()
{
MyType obj1,obj2;
Console.WriteLine("*****Learning reference Philosophy*****");
obj2=new MyType();
obj2.Name="Sadiq";
obj1=obj2;
Console.WriteLine("values of obj1={0} and obj2={1}",obj1.Name,obj2.Name);
obj1.Name="Ahmed";
Console.WriteLine("values of obj1={0} and obj2={1}",obj1.Name,obj2.Name);
}
}
当你编译并且运行这段代码时,你将得到如下输出:
*****Learning reference philosophy*****
values of obj1=Sadiq and obj2=Sadiq
values of obj1=Ahmed and obj2=Ahmed
第二程序:using System;
struct MyType
{
private string name;
public string Name
{
set
{
name=value;
}
get
{
return name;
}
}
}
class AppType
{
public static void Main()
{
MyType obj1,obj2;
Console.WriteLine("*****Learning reference Philosophy*****");
obj2=new MyType();
obj2.Name="Sadiq";
obj1=obj2;
Console.WriteLine("values of obj1={0} and obj2={1}",obj1.Name,obj2.Name);
obj1.Name="Ahmed";
Console.WriteLine("values of obj1={0} and obj2={1}",obj1.Name,obj2.Name);
}
}
我们再来看看上面代码运行后的输出:
*****Learning reference philosophy*****
values of obj1=Sadiq and obj2=Sadiq
values of obj1=Ahmed and obj2=Sadiq
为什么他们的输出不同?