使用 LINQ 将 C# 代码转换为 VB
本文关键字:转换 VB 代码 LINQ 使用 | 更新日期: 2023-09-27 18:36:28
我正在尝试将下面的 2 个例程转换为 VB,但我在使用免费的 Telerik 转换器时遇到了问题。 它通常工作得很好。
这些例程是 C# 扩展例程,用于查找与特定类型的控件或具有递归名称的控件匹配的窗口窗体控件:
public static IEnumerable<T> FindAllChildrenByType<T>(this Control control)
{
var controls = control.Controls.Cast<Control>();
var enumerable = controls as IList<Control> ?? controls.ToList();
return enumerable
.OfType<T>()
.Concat<T>(enumerable.SelectMany(FindAllChildrenByType<T>));
}
public static T FindChildByType<T>(this Control control, String ctrlName)
{
foreach (var ctrl in from ctrl in FindAllChildrenByType<T>(control) let testControl = ctrl as Control where testControl != null && testControl.Name.ToUpperInvariant() == ctrlName.ToUpperInvariant() select ctrl)
{
return ctrl;
}
return default(T);
}
我从Telerik网站得到的内容如下:
<System.Runtime.CompilerServices.Extension>
Public Function FindAllChildrenByType(Of T)(control As Control) As IEnumerable(Of T)
Dim controls As Control() = control.Controls.Cast(Of Control)()
Dim enumerable As IEnumerable = If(TryCast(controls, IList(Of Control)), controls.ToList())
Return enumerable.OfType(Of T).Concat(enumerable.SelectMany(AddressOf FindAllChildrenByType(Of T)))
End Function
<System.Runtime.CompilerServices.Extension>
Public Function FindChildByType(Of T)(control As Control, ctrlName As String) As T
For Each ctrl As T In From ctrl In FindAllChildrenByType(Of T)(control) Let testControl = TryCast(ctrl, Control) Where testControl IsNot Nothing AndAlso testControl.Name.ToUpperInvariant() = ctrlName.ToUpperInvariant() Select ctrl
Return ctrl
Next
Return Nothing
End Function
这些例程在 C# 中使用时工作得很好,我需要回到过去一点才能在 VB 中使用这些例程。
非常感谢!
唐·
转换有 2 个问题:
- 它没有使用选项 Infer On - 相当于"var"的 VB 是省略类型并使用 Option Infer On。这是第一种方法转换的唯一问题。转换器试图猜测这些并弄错了 - 无需猜测 - 让 Option Infer 执行此操作。
- 第二种方法在同一范围内使用"ctrl"两次 - 不知道为什么 C# 允许这样做。重命名每个变量的"外部"。
更正后的 VB 代码如下(请注意,扩展方法需要在"模块"内):
Option Infer On
Module Test
<System.Runtime.CompilerServices.Extension>
Public Function FindAllChildrenByType(Of T)(control As Control) As IEnumerable(Of T)
Dim controls = control.Controls.Cast(Of Control)()
Dim enumerable = If(TryCast(controls, IList(Of Control)), controls.ToList())
Return enumerable.OfType(Of T).Concat(enumerable.SelectMany(AddressOf FindAllChildrenByType(Of T)))
End Function
<System.Runtime.CompilerServices.Extension>
Public Function FindChildByType(Of T)(control As Control, ctrlName As String) As T
For Each ctrlx In From ctrl In FindAllChildrenByType(Of T)(control) Let testControl = TryCast(ctrl, Control) Where testControl IsNot Nothing AndAlso testControl.Name.ToUpperInvariant() = ctrlName.ToUpperInvariant() Select ctrl
Return ctrlx
Next
Return Nothing
End Function
End Module