对于 VB 中的每个函数

本文关键字:函数 VB 对于 | 更新日期: 2023-09-27 17:56:28

我不擅长 VB,我尝试在 VB 中转换以下 C# 函数,这让我遇到了很多错误......有人可以帮我将其转换为 VB 吗?

C#

foreach (Google.GData.Client.IExtensionElementFactory  property in  googleEvent.ExtensionElements)
        {
            ExtendedProperty customProperty = property as ExtendedProperty;
            if (customProperty != null)
                genericEvent.EventID = customProperty.Value;                
        }

我的转换有多个错误:

For Each Google.GData.Client.IExtensionElementFactory property in  googleEvent.ExtensionElements
            ExtendedProperty customProperty = property as ExtendedProperty
            If (customProperty <> null) Then
                genericEvent.EventID = customProperty.Value
            End If
        Next

对于 VB 中的每个函数

http://www.developerfusion.com/tools/convert/csharp-to-vb/

这将为您提供:

For Each [property] As Google.GData.Client.IExtensionElementFactory In googleEvent.ExtensionElements
    Dim customProperty As ExtendedProperty = TryCast([property], ExtendedProperty)
    If customProperty IsNot Nothing Then
        genericEvent.EventID = customProperty.Value
    End If
Next

如前所述,您可以使用自动化工具进行不使用更高级语言功能的琐碎转换。

但请注意:在 VB 中,As用于声明变量的类型 - 而不是像 C# 中那样的强制转换。

因此

For Each property As Google.GData.Client.IExtensionElementFactory In googleEvent.ExtensionElements
    Dim customProperty As ExtendedProperty = TryCast(property, ExtendedProperty)
    If customProperty IsNot Nothing Then
        genericEvent.EventID = customProperty.Value
    End If
Next
For Each elem As Google.GData.Client.IExtensionElementFactory In googleEvent.ExtensionElements
    Dim customProperty As ExtendedProperty = DirectCast(elem, ExtendedProperty)
    If ExtendedProperty IsNot Nothing Then
        genericEvent.EventID = customProperty.Value
    End If
Next

试试看

试试这个:

For Each property as Google.GData.Client.IExtensionElementFactory In googleEvent.ExtensionElements
     Dim customProperty As ExtendedProperty = CType(property, ExtendedProperty)
     If customerProperty IsNot Nothing Then
          genericEvent.EventID = customProperty.Value
     End If
Next
For Each property As Google.GData.Client.IExtensionElementFactory In googleEvent.ExtensionElements
    Dim customProperty As ExtendedProperty = TryCast(property, ExtendedProperty)
    If customProperty IsNot Nothing Then
        genericEvent.EventID = customProperty.Value
    End If
Next

VB.NET 的关键之一是它非常冗长。每当定义类型时,通常使用"名称As类型"。同样,null在 VB.NET 中Nothing,并且您不使用等于运算符在 VB.NET 中比较它。您使用IsIsNot .

最后,as强制转换,或者在失败时,它会在 C# 中返回null。在 VB.NET 中,您使用TryCast(而不是DirectCast)。

你很接近。主要问题是您的变量声明。

在 VB 中,声明几乎与 C# 相反。

我还没有测试过它或任何东西,但以下代码应该可以工作。

For Each [property] As Google.GData.Client.IExtensionElementFactory In googleEvent.ExtensionElements
    Dim customProperty as ExtendedProperty = [property]
    If customProperty IsNot Nothing Then
        genericEvent.EventID = customProperty.Value
    End If
Next