【发布时间】:2012-10-18 17:13:52
【问题描述】:
在下面的代码中,我试图让 TestClass 类中的方法(Work)更改主程序中某些变量的值,而不必返回它们。变量在 TestClass 构造函数中通过引用传递。
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
有没有办法让方法改变主程序中变量的值? 谢谢!
【问题讨论】:
-
您需要将 references 存储在
_a等中,但您刚刚将它们声明为ints。事实证明,CLR 不支持这个概念 - 你可以拥有作为引用但不是字段的局部变量。 But C# doesn't even let you declare such local variables.
标签: c# methods reference constructor parameter-passing