更改在范围外声明的变量或访问它

时间:2018-04-05 09:16:52

标签: c#

我不想声明x变量,但我想增加out y。可能吗?阿尔巴哈里代码。问题是y=1始终在初始化。我想检查y是否存在,然后y = y + 1;y = 0。想要访问并增加由我创建的变量。

using System;

namespace ConsoleAppX
{
    class D
    {
        static void Foo(out int y)
        {
            y = 1;
            y = y + 1; // Mutate y
        }

       // static int x;
        static void Main(string[] args)
        {
            Foo(out int x);
            Foo(out  x);
            Foo(out x);
            Console.WriteLine(x);
            Console.ReadLine();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

不知道你在尝试做什么:) 但是Out方法需要参数来赋值。

如果您不想分配任何值,只需操纵传递的值即可 您可以使用参考

所以你的代码看起来像,

using System;

namespace ConsoleAppX
{
    class D
    {
        static void Foo(ref int y)
        {
            //y = 1;
            y = y + 1; // Mutate y
        }

       // static int x;
        static void Main(string[] args)
        {
            int x = 0;
            Foo(ref x);
            Foo(ref x);
            Foo(ref x);
            Console.WriteLine(x);
            Console.ReadLine();
        }
    }
}