C#:结构

namespace ConsoleApplication8

{

public struct Dimensions

{

public double Height;

public double Width;

public Dimensions(double height, double width)

{

Height = height;

Width = width;

}

public double Diagonal

{

get

{

return Math.Sqrt(Height * Height + Width * Width);

}

}

static void Main(string[] args)

{

Dimensions test = new Dimensions(10, 10);

// 省去new关键字

/* Dimensions test;

test.Height = 10;

test.Width = 10; */

Console.WriteLine(test.Diagonal);

Console.ReadLine();

}

}

}

Sturct与Class的区别:

1. class 是引用类型,struct是值类型
既然class是引用类型,class可以设为null。但是我们不能将struct设为null,因为它是值类型。

namespace ConsoleApplication9

{

struct AStruct

{

int aField;

}

classAClass

{

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. structs 不可以有初始化器,class可以有初始化器。

class MyClass

{

int myVar = 10;  //  no syntax error.   

public void MyFun()

{      

//  statements

struct MyStruct

{

int myVar = 10;  //  syntax error[Cannot have instance field initializers in structs].  

public void MyFun()

{      

//  statements 

}

}

}

4. Class 可以有明显的无参数构造器,但是Struct不可以因为编译器总是提供一个无参数的默认构造函数,这是不允许替换的。

class MyClass

{

int myVar = 10;

public MyClass() // no syntax error. 

{

// statements

}

}

struct MyStruct

{

int myVar;

public MyStruct() // syntax error[Structs cannot contain explicit parameterless constructors].

{

// statements 

}

}

5. 类使用前必须new关键字实例化,Struct可以不需要

6. class支持继承和多态,Struct不支持. 注意:但是Struct 可以和类一样实现接口

 唯一的例外是结构派生于类System.Object. 结构的派生链是: 每个结构派生于System.ValueType,System.ValueType 派生于System.Object

7. 既然Struct不支持继承,其成员不能以protected 或Protected Internal 修饰

8. 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 control is returned to the caller ).

{

int myInt;

string myString;

public MyStruct(int aInt)

{

myInt = aInt;

}

}

9. Class可以定义析构器但是Struct不可以

10. Class比较适合大的和复杂的数据,Struct适用于作为经常使用的一些数据组合成的新类型。

适用场合:Struct有性能优势,Class有面向对象的扩展优势。
用于底层数据存储的类型设计为Struct类型,将用于定义应用程序行为的类型设计为Class。如果对类型将来的应用情况不能确定,应该使用Class。

原文地址:https://www.cnblogs.com/LilianChen/p/2935584.html