复制: When should I use a structure instead of a class?
只是想知道是否有人可以提供一些建议或示例,说明什么时候最好在.NET类上使用结构,或者反之亦然。
我做了一些背景阅读,并理解了两者之间的区别,即结构存储在堆栈上,类存储在堆上等等。但是,没有找到一些明显的例子,其中一个将提供一个好处的另一个。
非常感谢
发布于 2009-03-23 00:20:50
引用a good answer to the same question (When should I use a struct instead of a class?):
MSDN有答案:Choosing Between Classes and Structures.
基本上,这一页给你一个4项清单,并说使用一个类,除非你的类型符合所有的条件。
除非类型具有下列所有特征,否则不要定义结构:
发布于 2009-03-23 00:05:15
使用class
,除非您有非常具体的理由使用struct
。由于一些特定的原因,请参阅Questions about Structs。
编辑:与class
相比,struct
的一个可能的优点是您永远不能拥有null
实例。请参阅Is there a way to require that an argument provided to a method is not null?
发布于 2009-03-23 00:06:21
我更喜欢上课。
Structure TestStruct
Dim Name as String
End Structure
Dim x as TestStruct
If x Is Nothing Then
'ALWAYS returns false. A class would return true. Nullability, baby.
https://stackoverflow.com/questions/671847
复制相似问题