2015-11-05 58 views
0

我在C#以下代碼:C#傳結構作爲參數

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
namespace StrParameter 
{ 
    class Program 
    { 
     public struct RVector 
     { 
      private int ndim; 
      private double[] vector; 

      public RVector(int ndim) 
      { 
       this.ndim = ndim; 
       this.vector = new double[ndim]; 
       for (int i = 0; i < ndim; i++) 
       { 
        vector[i] = 0.0; 
       } 
      } 

      public RVector(double[] vector) 
      { 
       this.ndim = vector.Length; 
       this.vector = vector; 
      } 

      public double this[int i] 
      { 
       get 
       { 
        if (i < 0 || i > ndim) 
        { 
         throw new Exception("Requested vector index is out of range!"); 

        } 
        return vector[i]; 
       } 
       set { vector[i] = value; } 
      } 

      public override string ToString() 
      { 
       string str = "("; 
       for (int i = 0; i < ndim - 1; i++) 
       { 
        str += vector[i].ToString() + ", "; 
       } 
       str += vector[ndim - 1].ToString() + ")"; 
       return str; 
      } 
     } 

     static void SwapVectorEntries(RVector b,int m, int n) 
     { 
      double temp = b[m]; 
      b[m] = b[n]; 
      b[n] = temp; 
     } 

     static void Main(string[] args) 
     { 
      double[] a = new double[4] { 1, 2, 3, 4 }; 
      RVector b = new RVector(a); 
      Console.WriteLine(b); 
      SwapVectorEntries(b, 1, 2); //Why after this command, b will be changed ? 
      Console.WriteLine(b); 
     } 
    } 
} 

在這個程序中,我將創建一個結構RVector。之後,我使用一個方法SwapVectorEntries,它有一個struct參數。因爲Struct是value type,所以我認爲方法SwapVectorEntries不會更改結構參數。但是,在程序中,在命令SwapVectorEntries(b, 1, 2);之後,b已經改變。請給我解釋一下。謝謝 !

+1

你是不是修改結構,要修改的數組。數組不是值類型。將可變引用類型的結構聲明爲字段並不是一個好主意。 –

+0

另外,你可以跳過向量值的初始化(在'public RVector(int ndim)'構造函數中):在c#中,新創建的數組的每一項都會有它的默認值(0.0,在你的情況下使用double)。這不同於C/C++ –

+0

你也可以避免使用'ndim'成員變量:每次你需要它時,你可以用'vector.length'替換它。 –

回答

2

問題是this.You有一個數組至極是reference type。當你創建你

double[] a = new double[4] { 1, 2, 3, 4 }; 
RVector b = new RVector(a); 

你有兩個引用到array.After當你通過你的對象到方法,

SwapVectorEntries(b, 1, 2); 

你的對象被複制,但新對象有相同的參考到array.Here你的只有一個陣列和許多參考聽取它。

enter image description here

+0

但是,'b'是'RVector'結構的一個實例。它是通過使用帶有數組參數的構造函數創建的。所以,我認爲'b'是一種值類型。 –

+0

是b是一個值類型,但是當它作爲參數複製時,它的所有字段也會被複制,並且「double [] vector」是一個引用,它的值(數組的地址)也被複制。所以你有2個RVector的不同對象,但它們必須指向相同對象的向量。 –

+0

我編輯了我的asnwer.See –

2

B本身沒有作爲參考傳遞,但是b的副本有一個引用同樣的double[]