使用它們在下面的代碼中,我嘗試從類TestClass更改某些變量的值,而不必返回它們的主程序中的值。變量在TestClass構造函數中通過引用傳遞。C# - 通過引用傳遞參數給構造函數,然後從方法
class Program
{
static void Main(string[] args)
{
int a, b, c, d;
a = 5; b = 10; c = 20; d = 25;
Console.WriteLine("Main before TestClass: a=" + a + " b=" + b + " c=" + c + " d=" + d);
TestClass testObj = new TestClass(ref a,ref b,ref c,ref d);
testObj.Work();
Console.WriteLine("Main after TestClass: a=" + a + " b=" + b + " c=" + c + " d=" + d);
Console.ReadLine();
}
}
public class TestClass
{
int _a, _b, _c, _d;
public TestClass(ref int a, ref int b, ref int c, ref int d)
{
_a = a; _b = b; _c = c; _d = d;
}
public void Work()
{
Console.WriteLine("Work before changing: a=" + _a + " b=" + _b + " c=" + _c + " d=" + _d);
_a = 0; _b = 1; _c = 2; _d = 3;
Console.WriteLine("Work after changing: a=" + _a + " b=" + _b + " c=" + _c + " d=" + _d);
}
}
但是這個代碼返回:
Main before TestClass: a=5 b=10 c=20 d=25
Work before changing: a=5 b=10 c=20 d=25
Work after changing: a=0 b=1 c=2 d=3
Main after TestClass: a=5 b=10 c=20 d=25
有什麼辦法有方法改變主程序中的變量的值? 謝謝!
您需要在'_a'等中存儲*引用*,但您剛剛將它們聲明爲'int's。事實證明,CLR不支持這個概念 - 你*可以*具有引用的局部變量,但不包含字段。 [但是C#甚至不允許你聲明這樣的局部變量](http://blogs.msdn.com/b/ericlippert/archive/2011/06/23/ref-returns-and-ref-locals.aspx)。 –