加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-17 00:25:43 所属栏目:大数据 来源:网络整理
导读:以下VB.NET代码有效: Dim request As Model.LearnerLogbookReportRequest = New Model.LearnerLogbookReportRequestrequest.LearnerIdentityID = Convert.ToInt32(Session("identityID"))request.EntryVersion = LearnerLogbookEntryVersion.FullDim report
以下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:p4projectsWEB_DEVELOPMENTSECURE_ASPXmain-dev-codelinesLogbookSolution-DR6535RACQ.Logbook.WebRestfulSendLogbook.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 …我建议尽快使用它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读