从C/C++迈出C#世界的第一步,细节上有点模糊.据我所知,类默认通过引用传递,但是例如.列出<string>,如:
void DoStuff(List<string> strs)
{
//do stuff with the list of strings
}
Run Code Online (Sandbox Code Playgroud)
和其他地方
List<string> sl = new List<string>();
//next fill list in a loop etc. and then do stuff with it:
DoStuff(sl);
Run Code Online (Sandbox Code Playgroud)
是SL在这种情况下按引用传递或者是副本上进行,这样我需要重新定义,如工人功能
void DoStuff(ref List<string> strs)实际上是对sl本身采取行动而不是副本?
因此,如果我使用foreach循环进行迭代,并且我在内部有一个函数,它接受从列表迭代的对象的参数,并且假设我将其值设置为不同.我为什么不用出来或参考?我认为它只是通过值传递,如果你没有使用或参考....我知道你必须在前后初始化变量你必须在从方法返回之前设置它的值.
看起来如果你通过列表迭代并传递一个实际通过引用传递的对象.请考虑以下示例.
例
class Program
{
static void Main(string[] args)
{
List<Foo> list = new List<Foo>();
list.Add(new Foo() { Bar = "1" });
list.Add(new Foo() { Bar = "2" });
foreach (var f in list)
{
Foo f2 = f;
Console.WriteLine("SetFoo Pre: " + f2.Bar);
SetFoo(f2);
Console.WriteLine("SetFoo Post: " + f2.Bar);
Console.WriteLine("SetFooRef Pre: " + f2.Bar);
SetFooRef(ref f2);
Console.WriteLine("SetFooRef Post: " + f2.Bar);
Console.WriteLine("");
}
Console.WriteLine("");
int i = 0;
// Not using ref keyword
Console.WriteLine("SetI Pre: " + i); …Run Code Online (Sandbox Code Playgroud)