Overload Operator () VB.NET

I am new to VB.NET and am looking for a method to copy the behavior of a DataRow, for example. In VB.NET, I can write something like this:

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

Now, how can I access a member of my class using parentheses? I thought I could overload the () operator, but that doesn't seem to be the answer.

+6
source share
1 answer

This is not an overload operator, known as the default property .

"A class, structure, or interface can assign at most one of its properties as a default property, provided that the property accepts at least one parameter. If the code refers to a class or structure without specifying an element, Visual Basic resolves the reference to the default property." - MSDN -

Both the DataRowCollection and DataRow classes have a default Item property.

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

This allows you to write code without specifying the members of the Item :

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

Here is a simple example of a custom class with a default property:

 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" 

In the above example, you can use the default property for the string class to get the character at the specified position.

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

Source: https://habr.com/ru/post/976972/


All Articles