How to convert this general method from C # to VB.Net

I have the following code in C #

private void Synchronize<T>(TextSelection selection, DependencyProperty property, Action<T> methodToCall)
{ 
    object value = selection. GetPropertyValue(property) ;
    if ( value != DependencyProperty. UnsetValue) methodToCall((T) value) ;
} 

What I converted to VB.

Private Sub Synchronize(Of T)(ByVal selection As TextSelection, ByVal [property] As DependencyProperty, ByVal methodToCall As Action(Of T))
    Dim value As Object = selection.GetPropertyValue([property])
    If value IsNot DependencyProperty.UnsetValue Then
        methodToCall(DirectCast(value, T))
    End If
End Sub

The calling method looks like this:

Synchronize(Of Double)(selection, TextBlock.FontSizeProperty, AddressOf SetFontSize)
Synchronize(Of FontWeight)(selection, TextBlock.FontSizeProperty, AddressOf SetFontWeight)
Synchronize(Of FontStyle)(selection, TextBlock.FontStyleProperty, AddressOf SetFontStyle)
Synchronize(Of FontFamily)(selection, TextBlock.FontFamilyProperty, AddressOf SetFontFamily)
Synchronize(Of TextDecorationCollection)(selection, TextBlock.TextDecorationsProperty, AddressOf SetTextDecoration)

My problem is with calling DirectCast; if the delegate argument can be a simple type (integer, double, etc.) or an object. DirectCast does not like simple data types when an InvalidCastException occurs when I try to use a double. Does anyone have a suggested solution to this problem? I also tried TryCast, but I don't like mine (from T) and says it should be a limited class.

Thanks everyone!

Ryan

+3
source share
4 answers

Try using CType () instead of DirectCast ().

+1
source

, , , T , TryCast .

VB TryCast ( DirectCast, ), - [ , (Of T) → (Of T as Class)]:

Private Sub Synchronize(Of T as Class)(ByVal selection As TextSelection, ByVal [property] As DependencyProperty, ByVal methodToCall As Action(Of T)) 
    Dim value As Object = selection.GetPropertyValue([property]) 
    If value IsNot DependencyProperty.UnsetValue Then 
        methodToCall(TryCast(value, T)) 
    End If 
End Sub 
0

Use CType instead of TryCast / DirectCast. It should work like casting in C #:

methodToCall(CType(value, T))
0
source

You can put some restrictions on t

I believe the syntax looks something like this:

Private Sub Synchronize(Of T as {Class, Integer, Double})
0
source

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


All Articles