结构 struct 类 class
- 结构与类
类为引用类型,而结构为值类型 - 堆还是堆栈?
在类上调用“新建”(New) 运算符时,它将在堆上进行分配。但是,当实例化结构时,将在堆栈上创建结构。这样将产生性能增益。而且,您不会像对待类那样处理对结构实例的引用。您将直接对结构实例进行操作。鉴于此原因,向方法传递结构时,结构将通过值传递,而不是作为引用传递。 - 构造函数和继承
结构可以声明构造函数,但它们必须带参数。声明结构的默认(无参数)构造函数是错误的。结构成员不能有初始值设定项。总是提供默认构造函数以将结构成员初始化为它们的默认值。
使用 New 运算符创建结构对象时,将创建该结构对象,并且调用适当的构造函数。与类不同的是,结构的实例化可以不使用 New 运算符。如果不使用“新建”(new),那么在初始化所有字段之前,字段将保持未赋值状态,且对象不可用。
对于结构,不像类那样存在继承。一个结构不能从另一个结构或类继承,而且不能作为一个类的基。但是,结构从基类对象继承。结构可实现接口,而且实现方式与类实现接口的方式完全相同。
using System;
using System.Collections.Generic;
using System.Text;
namespace cappStruct
{
/// <summary>
/// myx.name
/// </summary>
class Program
{
static void Main(string[] args)
{
//struct
sContact ct = new sContact();
ct.m_name = "Mike";
ct.m_age = 25;
ct.m_tel = "123-456-789";
sContact ct2 = ct;
ct2.m_name = "Roger";
ct2.m_age = 23;
ct2.m_tel = "789-123-456";
Console.WriteLine("修改结构变量后:");
Console.WriteLine("Name:" + ct.m_name);
Console.WriteLine("Age:" + ct.m_age.ToString());
Console.WriteLine("Tel:" + ct.m_tel);
//class
cContact cc = new cContact();
cc.m_name = "Mike";
cc.m_age = 25;
cc.m_tel = "123-456-789";
cContact cc2 = cc;
cc2.m_name = "Roger";
cc2.m_age = 23;
cc2.m_tel = "789-123-456";
Console.WriteLine("修改类变量后:");
Console.WriteLine("Name:" + cc.m_name);
Console.WriteLine("Age:" + cc.m_age.ToString());
Console.WriteLine("Tel:" + cc.m_tel);
Console.WriteLine("按任意键退出……");
Console.ReadKey();
}
}
struct sContact
{
public string m_name;
public int m_age;
public string m_tel;
}
class cContact
{
public string m_name;
public int m_age;
public string m_tel = "Unknown";
}
}
using System.Collections.Generic;
using System.Text;
namespace cappStruct
{
/// <summary>
/// myx.name
/// </summary>
class Program
{
static void Main(string[] args)
{
//struct
sContact ct = new sContact();
ct.m_name = "Mike";
ct.m_age = 25;
ct.m_tel = "123-456-789";
sContact ct2 = ct;
ct2.m_name = "Roger";
ct2.m_age = 23;
ct2.m_tel = "789-123-456";
Console.WriteLine("修改结构变量后:");
Console.WriteLine("Name:" + ct.m_name);
Console.WriteLine("Age:" + ct.m_age.ToString());
Console.WriteLine("Tel:" + ct.m_tel);
//class
cContact cc = new cContact();
cc.m_name = "Mike";
cc.m_age = 25;
cc.m_tel = "123-456-789";
cContact cc2 = cc;
cc2.m_name = "Roger";
cc2.m_age = 23;
cc2.m_tel = "789-123-456";
Console.WriteLine("修改类变量后:");
Console.WriteLine("Name:" + cc.m_name);
Console.WriteLine("Age:" + cc.m_age.ToString());
Console.WriteLine("Tel:" + cc.m_tel);
Console.WriteLine("按任意键退出……");
Console.ReadKey();
}
}
struct sContact
{
public string m_name;
public int m_age;
public string m_tel;
}
class cContact
{
public string m_name;
public int m_age;
public string m_tel = "Unknown";
}
}
运行结果:
修改结构变量后
Name:Mike
Age:25
Tel:123-456-789
修改类变量后
Name:Roger
Age:23
Tel:789-123-456