我知道一个int是一个值类型,但是什么是值类型数组?参考类型?值类型?我想将数组传递给函数以检查某些内容。我应该只传递数组,因为它将只传递它的引用,还是应该将它作为ref传递?
我知道一个int是一个值类型,但是什么是值类型数组?参考类型?值类型?我想将数组传递给函数以检查某些内容。我应该只传递数组,因为它将只传递它的引用,还是应该将它作为ref传递?
Answers:
数组是使您可以将多个项目视为单个集合的机制。Microsoft®.NET公共语言运行时(CLR)支持一维数组,多维数组和锯齿状数组(数组的数组)。所有数组类型都隐式派生自System.Array,而System.Array本身派生自System.Object。这意味着 所有数组始终 是在托管堆上分配的引用类型,并且您的应用程序的变量包含对数组的引用,而不是数组本身。
数组(甚至是像int这样的值类型)都是C#中的引用类型。
http://msdn.microsoft.com/zh-CN/library/aa288453(VS.71).aspx:
在C#中,数组实际上是对象。System.Array是所有数组类型的抽象基类型。
首先,我想告诉您Array是引用类型。为什么?我在这里解释一个例子。
例:
int val = 0; // this is a value type ok
int[] val1 = new int[20] // this is a reference type because space required to store 20 integer value that make array allocated on the heap.
同样,引用类型可以为null,而值类型不能为null。
您可以使用out或ref将数组传递给函数。只有初始化方法不同。
测试以确认它是引用还是值类型:
// we create a simple array of int
var a1 = new int[]{1,2,3};
// copy the array a1 to a2
var a2 = a1;
// modify the first element of a1
a1[0]=2;
// output the first element of a1 and a2
Console.WriteLine("a1:"+a1[0]); // 2
Console.WriteLine("a2:"+a2[0]); // 2
//**************************
// all the two variable point to the same array
// it's reference type!
//**************************
您可以在线对其进行测试:https : //dotnetfiddle.net/UWFP45
//对数组的引用按值传递。这就是混乱的根源:-) ...
int[] test = { 1, 2, 3, 4 };
modifContenuSansRef(test);
Console.WriteLine(test[0]); // OK --> 99 le contenu du tableau est modifié
modifTailleSansRef(test);
Console.WriteLine(test.Length); // KO --> 4 La taille n'est pas modifiée
}
static void modifContenuSansRef(int[] t)
{
t[0] = 99;
}
static void modifTailleSansRef(int[] t)
{
Array.Resize(ref t, 8);
}
只是一点见识:
例如,int代表一个整数,int[]代表一个整数数组。
要使用特定尺寸初始化数组,可以使用new关键字,在类型名称后的方括号中给出大小:
//create a new array of 32 ints.
int[] integers = new int[32];
所有数组都是引用类型,并遵循引用语义。因此,在此代码中,即使各个元素都是原始值类型,但integers数组还是引用类型。因此,如果您以后再写:
int[] copy = integers;
这将简单地分配整个变量副本以引用同一数组,而不会创建新数组。
C#的数组语法很灵活,它允许您在不初始化数组的情况下声明数组,以便稍后可以在程序中动态调整数组的大小。使用这种技术,您基本上是在创建一个空引用,然后将该引用指向使用new关键字请求的动态分配的内存位置段:
int[] integers;
integers = new int[32];
谢谢。