C#经典面试题 C# 中 Struct 与 Class 的区别,以及两者的适用场合

在一家公司面试时,第一个问题就是问到这个

转载 文章 http://www.cnblogs.com/waitrabbit/archive/2008/05/18/1202064.html  来解释此问题

先说区别,原文出处 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

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。

 

posted on   新西兰程序员  阅读(313)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示