繁体   English   中英

C#输出参数,为什么我给我的变量赋值,仍然无法返回?

[英]c# out parameter, why I have assigned the value to my variable, still can't return?

我有一个简单的方法如下

        private int Increment(out n) {
            int n = 46;
            return n++;
        }

以我的理解,用完必须先初始化变量,但是我仍然得到以下错误

return n++ 

必须在控制离开当前方法之前将out参数'n'分配给

我也有我的变量错误

int n = 46;

无法在此范围内声明名为“ n”的本地或参数,因为该名称在封闭的本地范围内用于定义本地或参数

我的问题是,为什么我不能在方法内部声明新变量,似乎我必须在方法外部声明变量,然后在方法内部分配值。

如果我只是出去,那意味着我必须将变量int传递给我的方法,我不能在方法内部创建吗? 在我的方法中声明的参数指针之外?

out声明“声明”了变量,您只需要在方法中进行设置即可

private int Increment(out int n)
{
    n = 46;
    return n++;
}

请注意,此方法返回46,但n为47。

您可以这样编写方法。 它将返回完美的输出。

private int Increment(out int n)
{
    n = 46;
    n++;
    return n;
}

这将返回47作为输出。

不确定您要做什么,但这不是它的工作方式。 看一下示例(这不是递增数字的最简单方法,它只是refout参数的工作原理的POC)。

static void Main(string[] args)
{
    int incrementingNumber = 0;

    while(true)
    {
        Increment(ref incrementingNumber, out incrementingNumber);

        Console.WriteLine(incrementingNumber);
        Thread.Sleep(1000);
    }
}

private static void Increment(ref int inNumber ,out int outNumber)
{
    outNumber = inNumber + 46;
}

输出为:46 92 138 184 230 276 322 368 414 460 506 552

  1. 基本上,您没有正确声明n。
  2. 然后在函数(第3行)中,由于已经声明了n ,因此无法再次将其声明为int。
  3. 您的函数将始终返回46,因为您正在第3到46行中对其进行重新分配
  4. 您的函数将返回46,但会将n设置为47,我不确定这是否是您想要的。

如果只想增加1,则可以在任何地方运行此代码:

n++; // increment n by 1

n += 46; // increment n by 46

如果您真的想要一个函数,我怀疑您是否需要out int nreturn n

此代码将使变量n增加:

private static void Main()
{
    int n = 46;
    // some code here
    IncrementByOne(ref n);
    Console.WriteLine("N = " + n);
}    

/// this function will increment n by 1
private static void IncrementByOne(ref int n) { n++; }

此代码将返回一个递增的整数

private static void Main ()
{
    int n = 46;
    // some code here
    n = IncrementByOne(n);
    Console.WriteLine("N = " + n);
}    

/// this function will return an integer that is incremented by 1
private static int IncrementByOne(int n)
{
    n++; //increment n by one
    return n;
}

如果要在函数中声明n,则必须提前声明

static void Main(string[] args)
{
    int n = 46; // you have to set n before incrementing
    // some code here
    IncrementByOne(out n);
    Console.WriteLine("N = " + n);
}
/// this function will always set variable n to 47
private static void IncrementBy47(out int n)
{
    n = 46; // assign n to 46
    n++; // increase n by one
}

这也可以缩短为:

/// This function will always set variable n to 47
private static void SetVarTo47(out int n) { n = 47; }

希望有助于理解他们的工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM