C#struct中StructLayoutAttribute的优点是什么

C#struct中StructLayoutAttribute的优点是什么,c#,attributes,C#,Attributes,我遇到了use StructLayoutAttribute,但我不知道它对使用有什么帮助。我有一个类似的结构 [StructLayout(LayoutKind.Sequential)] public struct XYData { public int x; public int y; public XYData(int x, int y) { this.x = x; this.y = y; } } 应用Struct

我遇到了use StructLayoutAttribute,但我不知道它对使用有什么帮助。我有一个类似的结构

[StructLayout(LayoutKind.Sequential)]
public struct XYData
{

    public int x;

    public int y;

    public XYData(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

应用StructLayoutAttribute属性可以帮助我们吗

仅当此结构被封送到非托管代码时

如C中所述,已经对结构使用了
Sequential
。因此,从技术上讲,添加此属性没有影响:

C、VisualBasic和C++编译器默认地将顺序布局值应用于结构。

您可以在C#代码中将此值安全地添加到结构中,因为它将显式地记录意图,但它是可选的

如果您自己发射结构或直接使用IL,则需要指定它


请注意,对于类,如果您发现需要类中字段的特定布局,则需要直接指定
顺序

您的问题是什么?答案可能是否定的,并且您可能也不应该使用struct。。。但是在需要使用struct的地方描述您的问题可能会得到更详细的答案。没什么,struct的布局已经是连续的了。@AlexeiLevenkov哦,我不知道-一个
x
/
y
对对于
struct
来说不是一个坏的候选,只要它是由immutable@AlexeiLevenkov: 为了减少与自动值相关的布局相关问题,C语言、Visual Basic和C++编译器指定值类型的顺序布局。