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; }
}
}