我在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已經改變。請給我解釋一下。謝謝 !
你是不是修改結構,要修改的數組。數組不是值類型。將可變引用類型的結構聲明爲字段並不是一個好主意。 –
另外,你可以跳過向量值的初始化(在'public RVector(int ndim)'構造函數中):在c#中,新創建的數組的每一項都會有它的默認值(0.0,在你的情況下使用double)。這不同於C/C++ –
你也可以避免使用'ndim'成員變量:每次你需要它時,你可以用'vector.length'替換它。 –