【问题标题】:pass value by reference in constructor, save it, then modify it later, how to?在构造函数中通过引用传递值,保存它,然后再修改它,如何?
【发布时间】:2011-09-28 12:40:00
【问题描述】:

如何实现此功能?我认为它不起作用,因为我将它保存在构造函数中? 我需要做一些 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;
        }

    }

【问题讨论】:

    标签: c# parameters reference int


    【解决方案1】:

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

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

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

    您可能会发现 Eric Lippert 最近在 "ref returns and ref locals" 上的博文很有趣。

    【讨论】:

    • 谢谢,这真的很有帮助。
    【解决方案2】:

    你可以接近,但这实际上只是乔恩的变相回答:

     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
    

    【讨论】:

      猜你喜欢
      • 2012-10-18
      • 2014-12-21
      • 2014-05-28
      • 2012-03-19
      • 1970-01-01
      • 2017-08-12
      • 2013-10-12
      • 1970-01-01
      相关资源
      最近更新 更多