可能重复:
通过ref传入对象
使用下面的代码,输出将是:
Without:
With:1
Run Code Online (Sandbox Code Playgroud)
码:
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 });
}
Run Code Online (Sandbox Code Playgroud)
通过观察这个,我会说List上有一个List,所以无论如何都是由ref传递的,所以它们应该是一样的吗?我误解了ref关键字吗?还是我错过了别的什么?
任何人都可以解释在调用具有列表集合作为参数的方法时如何完成内存分配.由于下面的代码片段显然看起来似乎相同,但它不会产生相同的结果.所以我想知道方法调用在内存分配方面的区别.
using System;
using System.Collections.Generic;
namespace ListSample
{
class ListSampleClass
{
static void Main(string[] args)
{
List<int> i = new List<int>();
i.Add(10);
i.Add(15);
SampleMethod1(i);
Console.WriteLine("Result of SampleMethod1:"+i[0]);
SampleMethod2(i);
Console.WriteLine("Result of SampleMethod2:" + i[0]);
Console.ReadKey();
}
public static void SampleMethod1(List<int> i)
{
List<int> j = new List<int>();
j.Insert(0,20);
i = j;
}
public static void SampleMethod2(List<int> i)
{
List<int> j = new List<int>();
j = i;
j.Insert(0, 20);
}
}
}
Run Code Online (Sandbox Code Playgroud)