阵列参数通过在C#:为什么是隐含的参考?
-
25-09-2019 - |
题
假设以下代码时,没有任何 ref
关键词,这显然不会替代变量的通过,因为它是作为传递的价值。
class ProgramInt
{
public static void Test(int i) // Pass by Value
{
i = 2; // Working on copy.
}
static void Main(string[] args)
{
int i = 1;
ProgramInt.Test(i);
Console.WriteLine(i);
Console.Read();
// Output: 1
}
}
现在有这个功能的工作不如预期,一个将会增加的 ref
关键字像往常一样:
class ProgramIntRef
{
public static void Test(ref int i) // Pass by Reference
{
i = 2; // Working on reference.
}
static void Main(string[] args)
{
int i = 1;
ProgramInt.Test(ref i);
Console.WriteLine(i);
Console.Read();
// Output: 2
}
}
现在我困惑为什么阵成员当中传递的函数是隐含地通过参考。不阵值的类型?
class ProgramIntArray
{
public static void Test(int[] ia) // Pass by Value
{
ia[0] = 2; // Working as reference?
}
static void Main(string[] args)
{
int[] test = new int[] { 1 };
ProgramIntArray.Test(test);
Console.WriteLine(test[0]);
Console.Read();
// Output: 2
}
}
解决方案
没有,阵列的类,这意味着它们是引用类型。
其他提示
阵列不被引用传递。引用数组是按值传递。如果有必要改变什么阵列的传入的数组变量指向(例如,以改变所述阵列的大小),则变量必须通过引用传递。
一个很好的方式来记住这是:
- "参考",使得一个 别名 来一个 变量
- 阵列是一个 集合的变量;每个元素都是一个可变的。
当你通过一系列通常,你通过 集合的变量.变量集合中不会改变。
当你通过一系列的"参考",那么你是 给予一个新名称的变量包含阵列.
当你通过一系列元素通常,你通过 值的变量.
当你通过一系列因素-a的可变与"参考",你是 给予一个新的名称以这个变量.
有意义吗?
你能想象由值传递2000000元件阵列?现在想象一下,元素类型decimal
。你将不得不复制周围<击> 240MB 击> 30.5175781MB数据。
除了基本数据类型,你不能按值传递什么都为合格数组是基本数据类型也让路过的价值上征收会造成这将是对性能不好收集的多个副本的集合。
不隶属于 StackOverflow