相同点:⑴都是创建对象的模板,每个对象都包含数据,并提供处理和访问数据的方法;
⑵结构体和类在语法上很相似。
不同点:⑴结构体存储在内存的椎栈(stack)上,类存储在椎 (heap) 上;
⑵结构体使用struct关键字,类使用class关键字。
示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo9
{
class Program
{
static void Main(string[] args)
{
student name1 = new student();
name1.Name = "john";
Console.WriteLine(name1.Name);
teacher name2 = new teacher();
name2.Name = "teacher Wang";
Console.WriteLine(name2.Name);
}
struct student //声明一个student结构体
{
string name;
int age;
public string Name
{
set
{
this.name = value;
}
get
{
return this.name;
}
}
}
public class teacher //声明一个teacher类
{
string name;
int age;
public string Name
{
set
{
this.name = value;
}
get
{
return this.name;
}
}
}
}
}
浙公网安备 33010602011771号