为什么我的代码在VB.NET中编译,但C#中的等价代码失败了

前端之家收集整理的这篇文章主要介绍了为什么我的代码在VB.NET中编译,但C#中的等价代码失败了前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下VB.NET代码有效:
Dim request As Model.LearnerLogbookReportRequest = New Model.LearnerLogbookReportRequest
request.LearnerIdentityID = Convert.ToInt32(Session("identityID"))
request.EntryVersion = LearnerLogbookEntryVersion.Full

Dim reportRequestService As IReportRequestService = ServiceFactory.GetReportRequestService(ServiceInvoker.LearnerLogbook)
        reportRequestservice.SaveRequest(request)

以下C#代码无法编译:

LearnerLogbookReportRequest request = new LearnerLogbookReportRequest();
request.LearnerIdentityID = theLearner.ID;
request.EntryVersion = LearnerLogbookEntryVersion.Full;

IReportRequestService reportRequestService = ServiceFactory.GetReportRequestService(ServiceInvoker.LearnerLogbook);

reportRequestService.SaveRequest(ref request);

LearnerLogbookReportRequest声明为:

Public Class LearnerLogbookReportRequest
    Inherits AbstractReportRequest

错误

Error   11  Argument 1: cannot convert from 'ref RACQ.ReportService.Common.Model.LearnerLogbookReportRequest' to 'ref RACQ.ReportService.Common.Model.AbstractReportRequest'    C:\p4projects\WEB_DEVELOPMENT\SECURE_ASPX\main-dev-codelines\LogbookSolution-DR6535\RACQ.Logbook.Web\Restful\SendLogbook.cs 64  50  RACQ.Logbook.Web

为什么C#版本无法编译?

VB比ByRef参数更宽松,而不是C#.例如,它允许您通过引用传递属性. C#不允许这样做.

以类似的方式,在Option Strict关闭时,VB允许您使用参数,该参数是声明参数的子类型.作为一个简短但完整的计划,请考虑以下事项

Imports System

Public Class Test
    Public Shared Sub Main(args As String())
        Dim p As String = "Original"
        Foo(p)
        Console.WriteLine(p)
    End Sub

    Public Shared Sub Foo(ByRef p As Object)
        p = "Changed"
    End Sub
End Class

这适用于VB,但C#中的等价物不会……并且有充分的理由.这很危险.在这种情况下,我们使用字符串变量,我们碰巧更改p以引用另一个字符串,但是如果我们将Foo的主体更改为:

p = new Object()

然后我们在执行时得到一个异常:

Unhandled Exception: System.InvalidCastException: Conversion from type ‘Object’ to type ‘String’ is not valid.

基本上,ref在C#中是编译时类型安全的,但是在Option中关闭Option By的ByRef在类型上不是类型安全的.

如果你添加

Option Strict On

然而,在VB中的程序(或只是更改项目的默认值),您应该在VB中看到相同的问题:

error BC32029: Option Strict On disallows narrowing from type 'Object' to type
'String' in copying the value of 'ByRef' parameter 'p' back to the matching
argument.

        Foo(p)
            ~

这表明您目前正在编写没有Option Strict …我建议尽快使用它.

原文链接:https://www.f2er.com/vb/255229.html

猜你在找的VB相关文章