[英]Passing arguments by reference in static class methods
我收到錯誤消息“屬性或索引器可能無法作為輸出或引用參數傳遞”我的任務是將 buble 排序實現為靜態類,如果我將其設為非靜態,則它工作得很好。
public static class BubleSort
{
public static void Sort(List<int> arr)
{
for (int i = 0; i < arr.Count-1; i++)
{
var flag = true;
for (int j = 0; j < arr.Count-i-1; j++)
{
if (arr[j] > arr[j + 1])
{
Swap(ref arr[j],ref arr[j + 1]);
flag = false;
}
}
if (flag)
break;
}
}
private static void Swap(ref int v1,ref int v2)
{
int temp = v1;
v1 = v2;
v2 = temp;
}
}
你不能完全按照編譯器所說的原因做你想做的事情......但是你可以只使用列表的引用
private static void Swap(IList<int> list, int i)
{
int temp = list[i];
list[i] = list[i+1];
list[i+1] = temp;
}
或使用元組解構的 1 襯里
if (arr[j] > arr[j + 1])
{
(arr[j], arr[j + 1]) = (arr[j + 1], arr[j]);
flag = false;
}
Indexer access returns temporary value. 'ref' argument must be an assignable variable, field or an array element
您不能從列表發送引用,因為對特定索引元素的訪問是通過索引器完成的。 查看更多關於索引器
相反,您可以使用 ref 從數組int[]
發送引用,因為它不使用索引器,而是直接引用。
如果你仍然想使用列表,你可以使用 C# 特性來交換:
(arr[j],arr[j + 1]) = (arr[j + 1], arr[j]);
而不是Swap
方法
您的代碼將成為
public static class BubleSort
{
public static void Sort(List<int> arr)
{
for (int i = 0; i < arr.Count-1; i++)
{
var flag = true;
for (int j = 0; j < arr.Count-i-1; j++)
{
if (arr[j] > arr[j + 1])
{
(arr[j],arr[j + 1]) = (arr[j + 1], arr[j]);
flag = false;
}
}
if (flag)
break;
}
}
}
語言中有一個返回引用的功能。 但這僅適用於數組,而不是列表,因為列表可以重新分配。 因此,如果您將arr
更改為數組,我希望您的示例代碼能夠正常工作。 例如,請參閱此最小示例:
public void SwapTest()
{
var arr = new [] {1, 2};
Swap( ref arr[0], ref arr[1]);
}
public static void Swap(ref int a, ref int b)
{
var tmp = a;
a = b;
b = tmp;
}
但是,對於大多數實際應用,我建議使用@TheGeneral 發布的解決方案之一。 ref 返回有點不尋常,可能不是所有程序員都熟悉。
在這種情況下, arr[j] 被視為一個屬性,因為它需要讀取 List 中的一個字段。 屬性不是變量。 它們是方法,不能傳遞給 ref 參數。
如果你想這樣做,你需要將數組屬性傳遞給一個臨時變量。
例子:
if (arr[j] > arr[j + 1]){
int tempJ = arr[j];
int tempJ2 = arr[j + 1];
Swap(ref tempJ, ref tempJ2);
arr[j] = tempJ;
arr[j + 1] = tempJ2;
flag = false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.