[英]Why does this code for TcpClient work in vb.net, but not c#?
[英]Why does my code compile in VB.NET but the equivalent in C# fails
以下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 off时,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()
然后我们在执行时得到一个异常:
未处理的异常:System.InvalidCastException:从类型'Object'到类型'String'的转换无效。
基本上, ref
在C#中是编译时类型安全的,但是在Option中关闭Option 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 ...我建议尽快使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.