gpt4 book ai didi

C# - 通过对构造函数的引用传递参数,然后从方法中使用它们

转载 作者:太空狗 更新时间:2023-10-29 18:27:26 25 4
gpt4 key购买 nike

在下面的代码中,我试图让类 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

有没有办法让方法改变主程序中变量的值?谢谢!

最佳答案

您最好在 Int32 上创建自己的包装器以反射(reflect)更改,因为一旦将值分配给类的字段,它们就不再是引用,而是 Int32 的不同实例。考虑以下代码:

class Integer {
public int Value;

public Integer(int value) {
Value = value;
}

public override string ToString() {
return Value.ToString();
}
}

class TestClass {
Integer _a, _b, _c, _d;

public TestClass(Integer a, Integer b, Integer c, Integer d) {
_a = a;
_b = b;
_c = c;
_d = d;
}

public void Work() {
_a.Value = 111;
_b.Value = 222;
_c.Value = 333;
_d.Value = 444;
}
}

现在您有了一个 Integer -- Int32 的包装类。用法会给你带来结果:

Integer a = new Integer(0), b = new Integer(0), c = new Integer(0), d = new Integer(0);
Console.WriteLine("a: {0}, b: {1}, c: {2}, d: {3}", a, b, c, d);
new TestClass(a, b, c, d).Work();
Console.WriteLine("a: {0}, b: {1}, c: {2}, d: {3}", a, b, c, d);

输出是:

a: 0, b: 0, c: 0, d: 0
a: 111, b: 222, c: 333, d: 444

您可能还会发现阅读更多有关 C# 中的类和结构的信息很有用,例如http://msdn.microsoft.com/en-us/library/ms173109.aspx . (Int32 是一个结构,而在您的情况下您可能需要一个类)

关于C# - 通过对构造函数的引用传递参数,然后从方法中使用它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13120789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com