2011-11-29 93 views
1

正在获取:“结构无法被索引,因为它没有默认属性”。我究竟做错了什么?我在做什么错误:结构无法被索引,因为它没有默认属性(WITH CLAUSE)

With grid.Rows(10).Cells 
    Dim note As New Note With {.ID = "Blah", _ 
           .Date = "1/1/2011", _ 
           .Message = "AAA", _ 
           .Type = "ABC", _ 
           .SubType = "DEF", _ 
           .ReferenceKey = !SetRefNum.Value} 
End With 

,并注意样子:

Public Structure Note 
    Public Property ID As String 
    Public Property [Date] As Date 
    Public Property Message As String 

    Public Property Type As String 
    Public Property SubType As String 
    Public Property ReferenceKey As String 
End Structure 

回答

2

问题是与!SetRefNum.Value。您使用!运算符来引用集合中的索引,通常是字典。 Note类需要Default属性才能使用此术语。

Class Note 
    Public ReadOnly Default Property Item(Key As String) As String 
     Get 
      Return Settings(Key) 
     End Get 
    End Property 
    Private Settings As New Dictionary(Of String, String) 
End Class 

所以说,!SetRefNum.Value将转化为note.Item("SetRefNum.Value")

我会猜测你是在完全不同的东西之后。

查看成员访问操作员页面部分Special Characters in Code (Visual Basic)了解更多信息。

编辑:赞美回答赞扬的问题。

我建议以下方法:

With grid.Rows(10).Cells 
    Dim ReferenceKey As String = !SetRefNum.Value 
    Dim note As New Note With {.ID = "Blah", _ 
           .Date = "1/1/2011", _ 
           .Message = "AAA", _ 
           .Type = "ABC", _ 
           .SubType = "DEF", _ 
           .ReferenceKey = ReferenceKey} 
End With 

不知怎的,我怀疑会擦出火花。你可能需要这样的东西:

With grid.Rows(10).Cells 
    Dim ReferenceKey As String = .Item(SetRefNum.Value) 
+0

我遗漏了我的一部分代码......你是对的,这是在“WITH”块中。我改变了原来的帖子。 – Denis

+0

麻烦的是你有两个'With'块:有grid.Rows(10).Cells'和'With note'。请参阅经过编辑的建议答案 –

+0

就是这样!谢谢 – Denis

1

!字符用于C#中。对于VB,您需要使用Not关键字。因此,它应该是这样的:

Dim note As New Note With {.ID = "Blah", _ 
          .Date = "1/1/2011", _ 
          .Message = "AAA", _ 
          .Type = "ABC", _ 
          .SubType = "DEF", _ 
          .ReferenceKey = Not SetRefNum.Value} 

而且,假设你使用,因为在你的结构的自动属性的Visual Studio 2010中,您不需要尾随下划线。我会写这样的:

Dim note = New Note With {.ID = "Blah", 
          .Date = "1/1/2011", 
          .Message = "AAA", 
          .Type = "ABC", 
          .SubType = "DEF", 
          .ReferenceKey = Not SetRefNum.Value} 

编辑:那么,你的ReferenceKey字段是一个字符串,所以我不知道你要的布尔值。也许@手电子食品更接近正确的答案。

相关问题