C# 中 Struct 与 Class 的区别,以及两者的适用场合<转转转>

先说区别,原文出处 http://www.dotnetspider.com/resources/740-Difference-between-class-struct-C.aspx
1,class 是引用类型,structs是值类型
既然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 Class 可以有明显的无参数构造器,但是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。

posted @ 2010-04-16 17:46  一修先生  阅读(310)  评论(0编辑  收藏  举报