Are Vb.net/ delegates clearly introduced? Why does the compiler accept this "weakly typed" delegate?

I study delegates in VB.NET and am confused about delegate types. After reading about delegates, I learned that delegates are a data type that can refer to a method with a specific signature type. Thus, just as a String can refer to characters, a delegate can refer to a method (for example) that takes an integer as input and returns an integer as a result. But, playing with delegates, I found that this is not so. The code below compiles and runs, although I don’t obey the “typing” delegate in my subscription. I am embarrassed. Am I missing something?

Public Delegate Function myDelegate(ByVal i As Integer) As Integer' int in, rtrn int Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim md As myDelegate 'should be of type int in, rtrn int md = New myDelegate(AddressOf squared) 'allows assign to string in, string out MsgBox(md("3")) End Sub Private Function squared(ByVal i As String) As String Return i * i End Function 
+4
source share
1 answer

Yes, VB.NET is a strongly typed language, as well as delegates. But VB.NET inherits a lot of baggage from older versions of VB, such as implicit value conversion. The VB.NET compiler emits a call to Microsoft.VisualBasic.Conversions.ToDouble to "fix" conflicting types.

If you put Option Strict On at the top of your .vb file, you will see the errors you expect.

The Strict parameter restricts implicit data type conversion only when expanding conversions. The conversion extension explicitly does not allow data type conversions in which data loss can occur, or any conversion between numeric types and strings. For more information on expanding conversions, see Enhancing Conversions.

Link

+6
source

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


All Articles