类与结构的区别 ***a struct is implicitly sealed, a class isn't. ***a struct can't be abstract, a class can. ***a struct can't call : base() in its constructor whereas a class with no explicit base class can. ***a struct can't extend another class, a class can. ***a struct can't declare protected members (eg fields, nested types) a class can. ***a struct can't declare abstract function members, an abstract class can. ***a struct can't declare virtual function members, a class can. ***a struct can't declare sealed function members, a class can. ***a struct can't declare override function members, a class can. The one exception to this rule is that a struct can override the virtual methods of System.Object, viz, Equals(), and GetHashCode(), and ToString(). 记得这种区别有在中文网站看过,但这个比较详细点!
***a struct can't be abstract, a class can.
***a struct can't call : base() in its constructor whereas a class with no explicit base class can.
***a struct can't extend another class, a class can.
***a struct can't declare protected members (eg fields, nested types) a class can.
***a struct can't declare abstract function members, an abstract class can.
***a struct can't declare virtual function members, a class can.
***a struct can't declare sealed function members, a class can.
***a struct can't declare override function members, a class can. The one exception to this rule is that a struct can override the virtual methods of System.Object, viz, Equals(), and GetHashCode(), and ToString(). 记得这种区别有在中文网站看过,但这个比较详细点!
二 .类与结构的差别
1.值类型与引用类型 结构是值类型:值类型在堆栈上分配地址,所有的基类型都是结构类型,例如:int 对应System.int32 结构,string 对应 system.string 结构 ,通过使用结构可以创建更多的值类型 类是引用类型:引用类型在堆上分配地址 堆栈的执行效率要比堆的执行效率高,可是堆栈的资源有限,不适合处理大的逻辑复杂的对象。所以结构处理作为基类型对待的小对象,而类处理某个商业逻辑 因为结构是值类型所以结构之间的赋值可以创建新的结构,而类是引用类型,类之间的赋值只是复制引用 注: 1.虽然结构与类的类型不一样,可是他们的基类型都是对象(object),c#中所有类型的基类型都是object 2.虽然结构的初始化也使用了New 操作符可是结构对象依然分配在堆栈上而不是堆上,如果不使用“新建”(new),那么在初始化所有字段之前,字段将保持未赋值状态,且对象不可用 2.继承性 结构:不能从另外一个结构或者类继承,本身也不能被继承,虽然结构没有明确的用sealed声明,可是结构是隐式的sealed . 类:完全可扩展的,除非显示的声明sealed 否则类可以继承其他类和接口,自身也能被继承 注:虽然结构不能被继承 可是结构能够继承接口,方法和类继承接口一样
3.内部结构: 结构: 没有默认的构造函数,但是可以添加构造函数 没有析构函数 没?abstract 和 sealed(因为不能继承) 不能有protected 修饰符 可以不使用new 初始化 在结构中初始化实例字段是错误的 类: 有默认的构造函数 有析构函数 可以使用 abstract 和 sealed 有protected 修饰符 必须使用new 初始化 三.如何选择结构还是类 讨论了结构与类的相同之处和差别之后,下面讨论如何选择使用结构还是类: 1.堆栈的空间有限,对于大量的逻辑的对象,创建类要比创建结构好一些 2.结构表示如点、矩形和颜色这样的轻量对象,例如,如果声明一个含有 1000 个点对象的数组,则将为引用每个对象分配附加的内存。在此情况下,结构的成本较低。 3.在表现抽象和多级别的对象层次时,类是最好的选择 4.大多数情况下该类型只是一些数据时,结构时最佳的选择
补充c结构和c++类的区别:
C++ CLASS里的构造函数和析构函数可以在一个对象创建和销毁的时候自动执行的.
结构主要是针对特定的数据进行组织的,而类是具体对象的各种属性等的集合