zoukankan      html  css  js  c++  java
  • 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。

    作者:一修先生
             
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    Python集成开发环境搭建
    Windows10 解决 “/”应用程序中的服务器错误
    Windows系统清除远程连接记录的方法
    C# 处理DateTime算法,取某月第1天及最后一天
    SQL语句
    3389远程连接爆破实战
    SQL Server常用SQL集合
    VS2013、VS2015中,新建项目没有看到解决方案的问题(已解决)
    我的黑苹果装机篇
    C# 使用GZip对字符串压缩和解压
  • 原文地址:https://www.cnblogs.com/1971ruru/p/1713767.html
Copyright © 2011-2022 走看看