添加引用或退出关键字会使我出错“引用关键字可能无法传递参数1”,这会导致我的程序停止工作

时间:2019-05-15 15:26:20

标签: c#

我制作了一个只有一个参数的方法,即当我在main()中调用此方法并使用ref关键字将参数路径传递给它时,它只有一个成员。我reive error massage“参数1可能无法通过ref keword“

我试图删除ref keyworf,效果很好

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace learncsharp
{
    class Program
    {
        static int Value(int x)
       {
           x = 100;
           return x;
       }
        public static void Main()
        {
            int z = 10;
            Value(ref z);
            Console.Read();
        }
    }

 }

我期望得到sam结果达到10

1 个答案:

答案 0 :(得分:1)

定义为“ ref”的参数使您可以在完成后查看来自调用方的更改。

必须在函数中设置定义为“ out”的参数,并且可以看到完成后的值。

必须在函数头和函数调用中声明“ ref”或“ out”。

否则,参数将按值传递,并且所有更改都将丢失。

请注意,按值传递的对象在堆上共享相同的数据,因此调用者也可以看到对对象的属性/字段的任何更改,就好像它们是由'ref'

传递的一样。 使用您自己的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace learncsharp
{
    class Program
    {
        static int Value(ref int x)
       {
           x = 100;
           return x;
       }
        public static void Main()
        {
            int z = 10;
            Value(ref z);
            Console.Read();
        }
    }

 }