惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
WordPress大学
WordPress大学
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
The Cloudflare Blog
U
Unit 42
D
Docker
Hugging Face - Blog
Hugging Face - Blog
博客园 - 聂微东
Recent Announcements
Recent Announcements
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
Last Week in AI
Last Week in AI
V
Visual Studio Blog
I
InfoQ
Google DeepMind News
Google DeepMind News
小众软件
小众软件
L
LangChain Blog
C
Check Point Blog
宝玉的分享
宝玉的分享
Martin Fowler
Martin Fowler
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 【当耐特】
J
Java Code Geeks
罗磊的独立博客

博客园 - 太阳天子

汽车导航仪哪个好 JavaScript总结 A Programmers Overview Of C# .net中清除EXCEL进程最有效的方法 ADO.net 中数据库连接方式 浅析.Net下的多线程编程 .net如何实现页面间的参数传递 .NET组件和COM组件之间的相互操作 C#装箱拆箱和性能 asp.net中常用的一些小技巧 Microsoft SQL Server 2005 安装程序 错误解决 .net中的正则表达式使用高级技巧 (四)(from internet) net中的正则表达式使用高级技巧 (三)(from internet) .net中的正则表达式使用高级技巧 (二)(from internet) .net中的正则表达式使用高级技巧 (一)(from thinhunan's blog) ASP.NET 中的正则表达式(microsoft) 正则表达式语法(from internet) 正则表达式的基本语法 探索设计模式系列文章
结构和类
太阳天子 · 2006-05-16 · via 博客园 - 太阳天子

结构和类
结构是使用 struct 关键字定义的,例如:

C#  复制代码
public struct PostalAddress
            {
            // Fields, properties, methods and events go here...
            }
            

结构与类共享几乎所有相同的语法,但结构比类受到的限制更多:

  • 尽管结构的静态字段可以初始化,结构实例字段声明还是不能使用初始值设定项。

  • 结构不能声明默认构造函数(没有参数的构造函数)或析构函数。

结构的副本由编译器自动创建和销毁,因此不需要使用默认构造函数和析构函数。实际上,编译器通过为所有字段赋予默认值(参见默认值表)来实现默认构造函数。结构不能从类或其他结构继承。

结构是值类型 -- 如果从结构创建一个对象并将该对象赋给某个变量,变量则包含结构的全部值。复制包含结构的变量时,将复制所有数据,对新副本所做的任何修改都不会改变旧副本的数据。由于结构不使用引用,因此结构没有标识 -- 具有相同数据的两个值类型实例是无法区分的。C# 中的所有值类型本质上都继承自 ValueType,后者继承自 Object。

编译器可以在一个称为装箱的过程中将值类型转换为引用类型。有关更多信息,请参见装箱和取消装箱。

结构概述

结构具有以下特点:

  • 结构是值类型,而类是引用类型。

  • 向方法传递结构时,结构是通过传值方式传递的,而不是作为引用传递的。

  • 与类不同,结构的实例化可以不使用 new 运算符。

  • 结构可以声明构造函数,但它们必须带参数。

  • 一个结构不能从另一个结构或类继承,而且不能作为一个类的基。所有结构都直接继承自 System.ValueType,后者继承自 System.Object

  • 结构可以实现接口。

  • 在结构中初始化实例字段是错误的。

  1. What is the difference between a struct and a class in C#? - From language spec: The list of similarities between classes and structs is as follows. Longstructs can implement interfaces and can have the same kinds of members as classes. Structs differ from classes in several important ways; however, structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack or in-line. Careful programmers can sometimes enhance performance through judicious use of structs. For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements.