在构造函数中通过引用传递值,保存它,然后稍后修改它,如何?

Rya*_*Lee 7 c# parameters int reference

我该如何实现此功能?我认为它不起作用,因为我将它保存在构造函数中?我需要做一些Box/Unbox jiberish吗?

    static void Main(string[] args)
    {
        int currentInt = 1;

        //Should be 1
        Console.WriteLine(currentInt);
        //is 1

        TestClass tc = new TestClass(ref currentInt);

        //should be 1
        Console.WriteLine(currentInt);
        //is 1

        tc.modInt();

        //should be 2
        Console.WriteLine(currentInt);
        //is 1  :(
    }

    public class TestClass
    {
        public int testInt;

        public TestClass(ref int testInt)
        {
            this.testInt = testInt;
        }

        public void modInt()
        {
            testInt = 2;
        }

    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 12

基本上你不能.不是直接的."按引用传递"别名仅在方法本身内有效.

你最接近的是有一个可变的包装器:

public class Wrapper<T>
{
    public T Value { get; set; }

    public Wrapper(T value)
    {
        Value = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

Wrapper<int> wrapper = new Wrapper<int>(1);
...
TestClass tc = new TestClass(wrapper);

Console.WriteLine(wrapper.Value); // 1
tc.ModifyWrapper();
Console.WriteLine(wrapper.Value); // 2

...

class TestClass
{
    private readonly Wrapper<int> wrapper;

    public TestClass(Wrapper<int> wrapper)
    {
        this.wrapper = wrapper;
    }

    public void ModifyWrapper()
    {
        wrapper.Value = 2;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可能会发现Eric Lippert最近关于"ref return and ref locals"的博客文章很有趣.