我是VB.NET的新手,并且搜索一种复制DataRow行为的方法。 在VB.NET中,我可以写这样的东西:
Dim table As New DataTable
'assume the table gets initialized
table.Rows(0)("a value") = "another value"
现在如何使用括号访问班级成员?我以为我可以重载()运算符,但这似乎不是答案。
答案 0 :(得分:7)
它不是重载运算符,称为default property。
"类,结构或接口最多可以指定其属性之一作为默认属性,前提是该属性至少需要一个参数。如果代码在未指定成员的情况下引用类或结构,则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)