问题
Possible Duplicate:
passing in object by ref
With the code below, the output would be:
Without:
With:1
Code:
static void Main(string[] args)
{
var listWithoutRef = new List<int>();
WithoutRef(listWithoutRef);
Console.WriteLine("Without:" + string.Join(" ", listWithoutRef));
var listWithRef = new List<int>();
WithRef(ref listWithRef);
Console.WriteLine("With:" + string.Join(" ", listWithRef));
}
static void WithoutRef(List<int> inList)
{
inList = new List<int>(new int[] { 1 });
}
static void WithRef(ref List<int> inList)
{
inList = new List<int>(new int[] { 1 });
}
By just looking at this, I would have said that a List is on the Heap, and so is passed by ref anyway, so they should be the same? Am I misunderstanding the ref keyword? Or am I missing something else?
回答1:
Am I misunderstanding the ref keyword? Or am I missing something else?
Yes. You're not passing the list itself to the method, but rather passing the reference to the list by reference. This lets you change the reference (the List<int>
that listWithRef
actual refers to) within the method, and have it reflect.
Without using the ref
keyword, your method can't change the reference to the list - the actual list storage mechanism is unchanged in either case.
Note that this isn't required if you just want to use the list. You can call List<int>.Add
within either method, for example, and the list will get new items added to it. Ref is only required with reference types to change the reference itself.
回答2:
Yes, all of the List
objects are stored on the heap either way. However, without the ref
keyword, you can't reassign the inList
parameter and have it affect the caller's scope. When you create a new List
object, it goes on the heap as a new object, but the original reference in the caller's scope is not affected unless you use the ref keyword.
In WithoutRef
, if you call methods on the existing List
without redefining it, you will see that it is modified:
inList.Clear();
inList.Add(1);
来源:https://stackoverflow.com/questions/11213679/passing-listint-by-ref