C# 和 VB.Net 输出参数

标签 c# vb.net parameters out

我有一个用 c# 编写的项目,它正在使用另一个用 vb.net 编写的项目。我目前能够修改两者。

我在 VB 项目中有一个方法,例如:

    Public Sub MethodName(ByVal param1 As String, ByRef param2 As String)
        param2 = param1 + 1
    End Sub

我无法使用 C# 中的 out 关键字调用此方法:

    public void CallOtherMethod()
    {
        string param1 ="test";
        string param2;

        provider.AddTransaction(param1, out param2);
    }

VB.Net 中的 ByRef 关键字不应该同时具有“ref”和“out”的功能吗?

我应该直接去 ref 吗?

最佳答案

对于运行时来说,refout 是完全可以互换的,因为它们都只是传递一个引用。 但是out 在 IL 中带有附加属性前缀:

public void y(ref int a)
public void z(out int a)

变成

.method public hidebysig instance void  y(int32& a)
.method public hidebysig instance void  z([out] int32& a)

这使 C# 编译器能够区分这两个 添加 out 具有的特殊语义,即 out 参数不需要在进入方法之前有一个分配的值,并且必须在退出方法之前分配一个值。

相比之下,VB中的ByRef只提供了ref,而没有提供out的附加语义。在 VB 中,它不等同于 out

关于C# 和 VB.Net 输出参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6979648/

相关文章:

c# - 如何在 C# 中最小化 protected 属性

c# - SMO "Restore failed for Server"从文件恢复备份

c# - .NET从本地报告读取ReportParameter

c# - 在一页通用应用程序wp8.1中支持横向

c# - VS 2005 工具箱类控件.NET

python - 函数参数中空列表的值,示例here

vb.net - 何时检查碰撞

c# - 创建自己的异常(exception)

c# - 将参数传递给 json webservice

tsql - 从 SSRS 中的 ExecutionLog 中分割参数(字符串函数)