Struct - Layout.Explicit - 构造函数 - 完全分配字段

时间:2012-02-07 10:41:57

标签: c# struct

为什么我使用:

struct MyStruct
{
        [FieldOffset (0)] public uint Data;
        [FieldOffset (0)] public byte Something;
}

public MyStruct (uint pData)
{
   Data = pData; // setting Data field also sets Something field
}

C#说我需要分配'Something'字段:/我知道我可以做一个“构造函数:this()” 但编译器应该知道'数据'字段包含'Something'字段。

所以,我应该先调用无参数构造函数,这是唯一的方法吗?

3 个答案:

答案 0 :(得分:5)

是的,您需要调用默认构造函数。

Sub LOOKUP()   
  Dim myFilename As String
  Dim JCNames(2) As String
  Dim JCMails(2) As String
 JCNames = Array("x", "Y")
 JCMails = Array("X@rvnt.co.uk", "Y@rvnt.co.uk")
 Dim i As Long
 Dim j As Integer

j = 0
For i = 0 To UBound(JCNames)
myFilename = JCNames(i) & Format(Now(), "ddmmyyyy")

Range("G1").Select
ActiveSheet.Range("A:N").AutoFilter Field:=7, Criteria1:=JCNames(i)

With ActiveSheet
         lRows = .Cells(.Rows.Count, "B").End(xlUp).Row
         lCols = .Cells(1, .Columns.Count).End(xlToLeft).Column
         .Range(Cells(1, 1), Cells(lRows, lCols)).Copy
End With
Workbooks.Add

Range("A1").Select
ActiveSheet.Paste
Columns.AutoFit

ActiveWorkbook.SaveAs Filename:=myFilename, FileFormat:=xlOpenXMLWorkbook

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

On Error Resume Next
With OutMail
    .To = JCMails(i)
    .CC = ""
    .BCC = ""
    .Subject = "delays for" & JCNames
    .Body = "Hi there" & JCNames
    .Attachments.Add ActiveWorkbook.FullName
    .Display   'or use .Display
End With
On Error GoTo 0

Set OutMail = Nothing
Set OutApp = Nothing
i = i + 1
j = j + 1
Next i
end sub

然后,编译器将在构造函数的开头生成以下IL指令:

public MyStruct (uint pData) : this()
{
   //...
}

答案 1 :(得分:0)

似乎不可能,关于它的讨论已被关闭:

以下是有关此问题的讨论的链接:

https://github.com/dotnet/roslyn/issues/7323

答案 2 :(得分:-2)

如果定义自定义构造函数,则需要初始化结构的所有字段。有关详细信息,请参阅结构中的this MSDN教程 - 特别是在构造函数和继承标题下。

以下是从该链接中提取的与此相关的段落:

  

结构可以声明构造函数,但它们必须带参数。声明struct的默认(无参数)构造函数是错误的。 Struct成员不能有初始化器。始终提供默认构造函数以将结构成员初始化为其默认值。