【问题标题】:How would I translate the following statement into Visual Basic code?如何将以下语句转换为 Visual Basic 代码?
【发布时间】:2021-06-09 13:18:56
【问题描述】:

这是一个sn-p的代码:

    Dim gotoAction As PDFGoToAction = New PDFGoToAction()
        ' //PDF4NET 5: gotoAction.Destination = new PDFPageDestination();
        gotoAction.Destination = New PDFPageDirectDestination()
        '//PDF4NET 5: gotoAction.Destination.Page = destinationPage;
        (gotoAction.Destination as PDFPageDirectDestination).Page = destinationPage;

我遇到的问题是以下行:

(gotoAction.Destination as PDFPageDirectDestination).Page = destinationPage;

在 C# 中允许以这种方式强制转换此对象,但在 Visual Basic 中则不允许。我一直在网上搜索示例,但找不到上述语句的 Visual Basic 版本。

【问题讨论】:

  • 对不起,是的。你是对的!
  • 您正在寻找TryCast,而VB 不使用分号终止符。顺便说一句,您可以通过写Dim gotoAction As PDFGoToAction = New PDFGoToAction() With { Destination = New PDFPageDirectDestination() With {Page = destinationPage} } 来避免这种情况
  • 这能回答你的问题吗? VB.NET equivalent of C# "As"
  • 我建议DirectCast(gotoAction.Destination, PDFPageDirectDestination).Page = destinationPage,因为gotoAction.Destination 显然是PDFPageDirectDestination 对象。不清楚为什么不能只分配gotoAction.Destination.Page = destinationPage:您在此之前的一行创建了一个PDFPageDirectDestination 类型的新gotoAction.Destination 对象。
  • 虽然TryCast 是直接翻译,但它不适合这种用法(但公平地说,它在 C# 中也是一个不好的选择)。当它出错时,它会给出一个误导性的 NullReferenceException,而不是(如果使用直接转换正确完成)一个 InvalidCastException。用 C# 编写这一行的正确方法是 ((PDFPageDirectionDestination)gotoAction.Destination).Page = destinationPage;。 C# 中的 as 和 VB 中的 TryCast 仅应在将检查结果为 nullNothing 时使用。

标签: c# asp.net vb.net


【解决方案1】:

我认为您正在寻找的是DirectCast,您的代码可能是这样的:

DirectCast(gotoAction.Destination,PDFPageDirectDestination).page = destinationPage

这里有更多关于直接投射的信息:

https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/directcast-operator

【讨论】:

  • 正如 Charlieface 在评论中指出的那样,等效的是 TryCast,而不是 DirectCast。
  • @DaveDoknjas 虽然这不是 100% 准确的翻译,但DirectCast 是正确的方法。另请参阅我对这个问题的评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 2014-05-28
相关资源
最近更新 更多