我在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