1.class为引用类型,基类为system.Object ,struct为值类型,基类为system.ValueType,(system.ValueType为引用类型)
2.class可以声明无参构造函数,可以声明析构函数;而struct只能声明带参数构造函数,且不能声明析构函数。因此,struct没有自定义的默认无参构造函数,默认无参构造器只是简单地把所有值初始化为它们的0等价值
3.实例化时,class要使用new关键字;而struct可以不使用new关键字,如果不以new来实例化struct,则其所有的字段将处于未分配状态,直到所有字段完成初始化,否则引用未赋值的字段会导致编译错误。
4。• class实例由垃圾回收机制来保证内存的回收处理;而struct变量使用完后立即自动解除内存分配。
• 作为参数传递时,class变量是以按址方式传递;而struct变量是以按值方式传递的。
class Program
{
static void Main(string[] args)
{
//不使用NEW来生成
Farmily myfarmily;
myfarmily.name = "anytao farmily";
myfarmily.sex = true;
Console.WriteLine(myfarmily.name);
//使用new来生成
Farmily newfarmily=new Farmily("anytao farmily",26,true,"china",new Person("anytao",26));
Person p = new Person();
p.Name = "anytao";
//按值传递参数
ShowFarmily(newfarmily);
//按引用传递参数
ShowPerson(p);
newfarmily.GetSex();
newfarmily.ShowPerson();
Console.WriteLine(newfarmily.name);
Console.WriteLine(p.Name);
Console.WriteLine(newfarmily.ToString());
}
public static void ShowPerson(Person p)
{
p.Name = "ggg";
Console.WriteLine("This is {0}", p.Name);
}
public static void ShowFarmily(Farmily myfarmily)
{
myfarmily.name = "ttt";
Console.WriteLine("This is {0}",myfarmily.name);
}
}
struct Farmily:IPerson
{
public string name;
public int age;
public bool sex;
public string country;
public Person person;
//带参数的构造函数
public Farmily(string name,int age,bool sex,string country,Person person)
{
this.name = name;
this.age = age;
this.sex = sex;
this.country = country;
this.person = person;
}
#region IPerson 成员
public void GetSex()
{
if (sex)
Console.WriteLine(person.Name + "is a boy");
else
Console.WriteLine(person.Name+"is a gril");
}
#endregion
public void ShowPerson()
{
Console.WriteLine("This is {0} from {1}", new Person(name, 22).Name, country);
}
//可以重载ToString虚方法
public override string ToString()
{
return String.Format("{0} is {1}, {2} from {3}", person.Name, age, sex ? "Boy" : "Girl", country);
}
}
//定义类
public class Person
{
public Person()
{
}
//带参数的构造函数
public Person(string name, int age)
{
_name = name;
_age = age;
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
}