簡體   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