[英]How to Convert this generic method from C# to VB.Net
我在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調用; 如果我的委托參數可以是簡單類型(整數,雙精度等)或對象。 DirectCast不喜歡簡單的數據類型,當我嘗試強制轉換為double時拋出InvalidCastException。 有沒有人有這個問題的建議解決方案? 我也試過TryCast,但它不喜歡我的(T)並說它必須是類收縮的。
謝謝大家!
瑞安
嘗試CType()而不是DirectCast()。
查看您看到的錯誤,聽起來您可能需要在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
使用CType而不是TryCast / DirectCast。 它應該像C#中的轉換一樣工作:
methodToCall(CType(value, T))
你可以在t上加上多個約束
我相信語法是這樣的:
Private Sub Synchronize(Of T as {Class, Integer, Double})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.