Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.
2012-04-12
As always, I use Visual Basic in strict mode. I have this function that expects a Foo array:
Sub DoSomething(X() As Foo) Console.WriteLine(X.Length) End Sub
What I’m showing here is true for single variables too, but I am showing this using arrays. This cannot be called using an Integer array as follows:
DoSomething({1, 2, 3})
Adding a Integer constructor to the Foo class does not help. However, you can add a widening operator to the Foo class, and define how an implicit conversion is done, like so:
Public Class Foo Private mX As Integer Public Sub New(X As Integer) Me.mX = X End Sub Shared Widening Operator CType(X As Integer) As Foo Return New Foo(X) End Operator End Class
Now, both the above method call is accepted. And because this also works on arrays, this simple line constructs three Foo objects:
Dim X() As Foo = {4, 5, 6}
The equivalent with a single (non arrayed) object would look like this:
Dim Y As Foo = 7
The opposite to Widening is called Narrowing and is used to define explicit type casts.
Categories: VB.NET
Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!
Leave a Reply