gpt4 book ai didi

VB.NET 重载 () 运算符

转载 作者:行者123 更新时间:2023-12-04 11:51:30 26 4
gpt4 key购买 nike

我是 VB.NET 的新手,正在寻找一种方法来复制 DataRow 的行为,例如。
在 VB.NET 中,我可以这样写:

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

现在如何使用方括号访问我的类(class)成员?我以为我可以重载 () 运算符,但这似乎不是答案。

最佳答案

它不是重载运算符,这被称为 default property .

"A class, structure, or interface can designate at most one of its properties as the default property, provided that property takes at least one parameter. If code makes a reference to a class or structure without specifying a member, Visual Basic resolves that reference to the default property." - 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"

给定上面的示例,您可以使用 string 类的默认属性来获取指定位置的字符。
f(0) = "abc"
Dim c As Char = f(0)(1) '<- "b" | f.Test(0).Chars(1)

关于VB.NET 重载 () 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26464695/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com