![](/img/trans.png)
[英]How do I marshal wchar_t* from C++ to C# as an out parameter or return value?
[英]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作為輸出。
不確定您要做什么,但這不是它的工作方式。 看一下示例(這不是遞增數字的最簡單方法,它只是ref
和out
參數的工作原理的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
n
,因此無法再次將其聲明為int。 如果只想增加1,則可以在任何地方運行此代碼:
n++; // increment n by 1
n += 46; // increment n by 46
如果您真的想要一個函數,我懷疑您是否需要out int n
和return 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.