如何将此通用方法从C#转换为VB.Net
我在C#中有以下代码块 调用方法如下所示:如何将此通用方法从C#转换为VB.Net,c#,.net,c#-to-vb.net,C#,.net,C# To Vb.net,我在C#中有以下代码块 调用方法如下所示: Synchronize(Of Double)(selection, TextBlock.FontSizeProperty, AddressOf SetFontSize) Synchronize(Of FontWeight)(selection, TextBlock.FontSizeProperty, AddressOf SetFontWeight) Synchronize(Of FontStyle)(selection, TextBlock.FontS
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不喜欢简单的数据类型,当我尝试将InvalidCastException转换为double时会抛出InvalidCastException。有人对这个问题有什么建议吗?我也试过TryCast,但它不喜欢我的(of t),并且说它一定是一流的
谢谢大家
Ryan查看您看到的错误,听起来您可能需要在T句柄上添加一个约束,将其限制为类,以便使用TryCast 我对VB的TryCast方法(或者DirectCast)不是很熟悉,但是类似的东西可能会有所帮助[注意(T的)->(T的类)]:
使用CType而不是TryCast/DirectCast。它应该像C#中的铸件一样工作:
尝试CType()而不是DirectCast()。您可以对t设置多个约束 我相信语法是这样的:
Private Sub Synchronize(Of T as {Class, Integer, Double})
出于好奇,您是否尝试过删除DirectCast并只是传递值?@Tony-也不喜欢这样。表示指定的强制转换无效。我添加了一些代码,为这个问题提供了更多的上下文。Double和Integer不能满足类约束。请尝试。炸弹也会爆炸。我已经尝试了我知道的三种类型转换(CType、TryCast和DirectCast),但没有一种转换适用于所有情况。我只是用DirectCast和CType进行了测试。前者提出了一个无效的例外。后者运作良好。
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)
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
methodToCall(CType(value, T))
Private Sub Synchronize(Of T as {Class, Integer, Double})