2013-05-11 87 views
1

我是C#的新手,我無法理解爲什麼這段代碼不起作用。交換數組中2個元素的函數不起作用

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      char[] sw = "ab".ToCharArray(); 
      swap(sw[0], sw[1]); 
      string end = new string(sw); 
      Console.Write(end); 
     } 

     static void swap(char a, char b) 
     { 
      char temp = a; 
      a = b; 
      b = temp; 
     } 
    } 
} 

我在控制檯上的預期是「ba」,但我得到「ab」。我能夠找到解決這個問題的不同方法,但我想知道的是這個代碼中的錯誤。 感謝您的幫助!

回答

0

您按照價值傳遞您的論點ab
有關更多信息,請參閱What's the difference between passing by reference vs. passing by value?

以下是解決您的問題的兩種解決方案。

//Pass by value and return the values 
static Tuple<char, char> swap2(char a, char b) 
{ 
    char temp = a; 
    a = b; 
    b = temp; 
    return new Tuple<char, char>(a, b); 
} 

//Pass by reference 
static void swap3(ref char a, ref char b) 
{ 
    char temp = a; 
    a = b; 
    b = temp; 
} 

public static void Main(string[] args) 
{ 
    char[] sw2 = "ab".ToCharArray(); 
    var chars2 = swap2(sw2[0], sw2[1]); 
    sw2[0] = chars2.Item1; 
    sw2[1] = chars2.Item2; 
    //Will print "ba" 
    Console.WriteLine(sw2); 

    char[] sw3 = "ab".ToCharArray(); 
    swap3(ref sw3[0], ref sw3[1]); 
    //Will print "ba" 
    Console.WriteLine(sw3); 
} 

下面是關於是否應該使用或嘗試避免ref關鍵字的問題。除了最簡單的用途之外,通常建議儘可能避免參考。交換屬於「最簡單的用法」類別,但我建議您儘量避免在大多數實際情況下使用ref。
When is using the C# ref keyword ever a good idea?

+0

感謝,認爲C#做它總是由參,問題溶膠VED。 – user2373458 2013-05-11 18:24:58

8

的問題是,swap方法實際上只是操縱的ab本地副本。您需要通過引用傳遞參數。所以,你會定義swap方法是這樣的:

static void swap(ref char a, ref char b) 
    { 
     char temp = a; 
     a = b; 
     b = temp; 
    } 

,並調用它是這樣的:

swap(ref sw[0], ref sw[1]); 
+0

這可能是要走的路! – 2013-05-11 18:26:42

+0

@AlexBell我同意這可能是交換的方式,因爲它非常簡單。但我通常儘量避免使用ref關鍵字,因爲它往往會導致更復雜的API IMO。 – 2013-05-11 18:41:22

+0

這正是我所要做的,但使'Swap'通用,因此它適用於任何數組,然後將其放置在某些實用程序類中。 – Lukazoid 2017-04-18 11:38:05

0

你交換走的是兩條值類型和變量之間交換值。沒有什麼會修改原始數組。你會需要修改你的交換方法是這樣的:)像

static void Swap(char[] array, int a, int b) 
{ 
    char temp = array[a]; 
    array[a] = array[b]; 
    array[b] = temp; 
} 

然後,您可以從主(稱之爲:

Swap(array, 0, 1); 
1

應該像下面的(注進行修改:在這個例子中,ref char[] arr具有前綴ref主要用於教導目的:陣列將ref傳遞默認)

namespace ConsoleApplication1 
{ 

     class Program 
     { 
      static void Main(string[] args) 
      { 
       char[] sw = "ab".ToCharArray(); 
       swap(0, 1, ref sw); 
       string end = new string(sw); 
       Console.Write(end); 
      } 

      static void swap(int indexA, int indexB, ref char[] arr) 
      { 
       char temp = arr[indexA]; 
       arr[indexA] = arr[indexB]; 
       arr[indexB] =temp; 
      } 
     } 
    }