什么时候应该在C#中使用结构而不是类?我的概念模型是,当项只是值类型的集合时,使用结构。一种将它们逻辑地结合在一起的方法。

我在这里遇到了这些规则:

结构应表示单个价值结构应具有内存占用空间小于16字节。结构不应在之后更改创造

这些规则有效吗?结构在语义上意味着什么?


当前回答

第一:互操作场景或需要指定内存布局时

第二:当数据大小与引用指针几乎相同时。

其他回答

我认为一个好的第一近似值是“从不”。

我认为一个好的二次近似是“从不”。

如果你渴望表现,那么考虑一下,但始终要衡量。

在需要使用StructLayoutAttribute显式指定内存布局(通常用于PInvoke)的情况下,需要使用“结构”。

编辑:注释指出,可以将类或结构与StructLayoutAttribute一起使用,这当然是正确的。在实践中,您通常会使用一个结构——它是在堆栈上分配的,而不是在堆上分配的——如果您只是向非托管方法调用传递一个参数,这是有意义的。

结构是值类型。如果将结构分配给新变量,则新变量将包含原始变量的副本。

public struct IntStruct {
    public int Value {get; set;}
}

执行以下操作将导致存储在内存中的结构的5个实例:

var struct1 = new IntStruct() { Value = 0 }; // original
var struct2 = struct1;  // A copy is made
var struct3 = struct2;  // A copy is made
var struct4 = struct3;  // A copy is made
var struct5 = struct4;  // A copy is made

// NOTE: A "copy" will occur when you pass a struct into a method parameter.
// To avoid the "copy", use the ref keyword.

// Although structs are designed to use less system resources
// than classes.  If used incorrectly, they could use significantly more.

类是引用类型。将类分配给新变量时,该变量包含对原始类对象的引用。

public class IntClass {
    public int Value {get; set;}
}

执行以下操作只会导致内存中类对象的一个实例。

var class1 = new IntClass() { Value = 0 };
var class2 = class1;  // A reference is made to class1
var class3 = class2;  // A reference is made to class1
var class4 = class3;  // A reference is made to class1
var class5 = class4;  // A reference is made to class1  

结构可能会增加代码错误的可能性。如果将值对象视为可变引用对象,那么当所做的更改意外丢失时,开发人员可能会感到惊讶。

var struct1 = new IntStruct() { Value = 0 };
var struct2 = struct1;
struct2.Value = 1;
// At this point, a developer may be surprised when 
// struct1.Value is 0 and not 1

Struct可用于提高垃圾收集性能。虽然您通常不必担心GC性能,但在某些情况下,它可能是一个杀手。就像低延迟应用程序中的大型缓存。请参阅本帖中的示例:

http://00sharp.wordpress.com/2013/07/03/a-case-for-the-struct/

这是一条基本规则。

如果所有成员字段都是值类型,则创建一个结构。如果任何一个成员字段是引用类型,请创建一个类。这是因为引用类型字段无论如何都需要堆分配。

Exmaples公司

public struct MyPoint 
{
    public int X; // Value Type
    public int Y; // Value Type
}

public class MyPointWithName 
{
    public int X; // Value Type
    public int Y; // Value Type
    public string Name; // Reference Type
}