передать значение по ссылке в конструкторе, сохранить его, а затем изменить его, как? - PullRequest
7 голосов
/ 05 июля 2011

Как мне реализовать эту функцию? Я думаю, что это не работает, потому что я сохраняю его в конструкторе? Нужно ли мне делать jiberish Box / Unbox?

    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;
        }

    }

Ответы [ 2 ]

12 голосов
/ 05 июля 2011

Вы не можете, в основном.Не напрямую.Псевдоним «передача по ссылке» действителен только в самом методе.

Самое близкое, что вы могли бы получить - это изменяемая оболочка:

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

    public Wrapper(T value)
    {
        Value = value;
    }
}

Тогда:

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;
    }
}

Вы можете найти интересное недавнее сообщение Эрика Липперта в блоге "ref return и ref localals" *. 1011 *

0 голосов
/ 05 июля 2011

Вы можете приблизиться, но это действительно замаскированный ответ Джона:

 Sub Main()

     Dim currentInt = 1

     'Should be 1
     Console.WriteLine(currentInt)
     'is 1

     Dim tc = New Action(Sub()currentInt+=1)

     'should be 1
     Console.WriteLine(currentInt)
     'is 1

     tc.Invoke()

     'should be 2
     Console.WriteLine(currentInt)
     'is 2  :)
 End Sub
...