既然class是引用類型,class可以設為null。但是我們不能將struct設為null,因為它是值類型。
struct AStruct
{
int aField;
}
class AClass
{
int aField;
}
class MainClass
{
public static void Main()
{
AClass b = null; // No error.
AStruct s = null; // Error [ Cannot convert null to 'AStruct'because it is a value type ].
}
}
2,當妳實例化壹個class,它將創建在堆上。而妳實例化壹個struct,它將創建在棧上
3,妳使用的是壹個對class實例的引用。而妳使用的不是對壹個struct的引用。(而是直接使用它們)
4,當我們將class作為參數傳給壹個方法,我們傳遞的是壹個引用。struct傳遞的是值而非引用。
5,structs 不可以有初始化器,class可以有初始化器。
class MyClass
{
int myVar =10; // no syntax error.
public void MyFun( )
{ // statements }
}
struct MyStruct
{
int myVar = 10; // syntax error.
public void MyFun( )
{// statements }
}
6,Classes 可以有明顯的無參數構造器,但是Struct不可以
class MyClass
{
int myVar = 10;
public MyClass( ) // no syntax error.
{
// statements
}
}
struct MyStruct
{
int myVar;
public MyStruct( ) // syntax error.
{
// statements
}
}
7,類使用前必須new關鍵字實例化,Struct不需要
MyClass aClassObj; // MyClass aClassObj=new MyClass(); is the correct format.aClassObj.
myVar=100;//NullReferenceException(because aClassObj does not contain a reference to an object of type myClass).
MyStruct aStructObj;
aStructObj.myVar=100; // no exception.
8,class支持繼承和多態,Struct不支持. 註意:但是Struct 可以和類壹樣實現接口
9,既然Struct不支持繼承,其成員不能以protected 或Protected Internal 修飾
10,Class的構造器不需要初始化全部字段,Struct的構造器必須初始化所有字段
class MyClass //No error( No matter whether the Field ' MyClass.myString ' is initialized or not ).
{
int myInt;
string myString;
public MyClass( int aInt )
{ myInt = aInt; }
}
struct MyStruct // Error ( Field ' MyStruct.myString ' must be fully assigned before it leaves the constructor ).
{
int myInt;
string myString;
public MyStruct( int aInt )
{
myInt = aInt;
}
}
11,Class可以定義析構器,但是Struct不可以
12,Class比較適合大的和復雜的數據,Struct適用於作為經常使用的壹些數據組合成的新類型。
適用場合:Struct有性能優勢,Class有面向對象的擴展優勢。
用於底層數據存儲的類型設計為Struct類型,將用於定義應用程序行為的類型設計為Class。如果對類型將來的應用情況不能確定,應該使用Class。