2014-10-20 63 views
6

我是VB.NET新手,并且搜索复制DataRow行为的方法。 在VB.NET我可以写这样的事:VB.NET overload()运算符

Dim table As New DataTable 
'assume the table gets initialized 
table.Rows(0)("a value") = "another value" 

现在,我怎么能访问我用括号类的成员?我以为我可以超载()运营商,但这似乎不是答案。

+3

Indexer? [如何在Visual Basic .NET中创建索引器属性](http://support.microsoft.com/kb/311323) – 2014-10-20 11:37:54

+2

'()'不是运算符。它是如何访问一系列的东西。你的例子中的第二组是'Rows(0)'的单元或项目集合 – Plutonix 2014-10-20 11:39:08

回答

6

这不是一个超载操作符,这被称为default property

“A类,结构或界面可以指定其属性的默认属性的至多一个,条件是属性接受的至少一个参数。如果代码使对类或结构的引用而不指定成员,Visual Basic解决了对默认属性的引用。“ - MSDN -

无论是DataRowCollection类和DataRow类有一个名为Item的默认属性。

  |  | 
table.Rows.Item(0).Item("a value") = "another value" 

这允许你写的代码,而无需指定Item成员:

table.Rows(0)("a value") = "another value" 

这里有一个自定义类具有默认属性的一个简单的例子:

Public Class Foo 

    Default Public Property Test(index As Integer) As String 
     Get 
      Return Me.items(index) 
     End Get 
     Set(value As String) 
      Me.items(index) = value 
     End Set 
    End Property 

    Private ReadOnly items As String() = New String(2) {"a", "b", "c"} 

End Class 

Dim f As New Foo() 
Dim a As String = f(0) 

f(0) = "A" 

考虑到上面的例子,您可以使用字符串类的默认属性来获取指定位置的字符。

f(0) = "abc" 
Dim c As Char = f(0)(1) '<- "b" | f.Test(0).Chars(1)