如何将这个C#通用方法转换为VB.Net?

3

我在C#中有以下代码块:

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

我已经将其转换为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

呼叫方法如下所示:
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)

我的问题出在 DirectCast 调用上;如果我的委托参数可以是一个简单类型(整数,双精度等)或对象。当我尝试强制转换为 double 时,DirectCast 不喜欢简单数据类型,会抛出 InvalidCastException。有人有解决这个问题的建议吗?我也尝试过 TryCast,但它不喜欢我的 (of T),并说它必须是类约束。
谢谢大家!
Ryan

你出于好奇尝试过删除DirectCast,直接传入值吗? - Tony Abrams
@Tony - 我也不喜欢那个。显示指定的转换无效。我添加了一些代码以更好地描述问题的上下文。 - Ryan
4个回答

1

尝试使用CType()而不是DirectCast()。


尝试过了,但还是失败了。我已经尝试了我知道的三种类型转换(CType、TryCast 和 DirectCast),但都不能适用于所有情况。 - Ryan
我刚刚使用了DirectCast和CType进行测试。前者引发了InvalidCastException异常,而后者正常工作。 - Eyal

0

使用CType而不是TryCast/DirectCast。它应该像C#中的转换一样工作:

methodToCall(CType(value, T))

0

从您看到的错误来看,似乎您需要在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 

Double和Integer不满足类约束。 - Matthieu

0

您可以对 t 应用多个约束条件。

我相信语法应该是这样的:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接