简体   繁体   English

对在C#中传递ref / value感到困惑

[英]Confused about passing by ref/value in c#

As in the title something just hasn't clicked for me yet as i'm still learning c#, the following is some really basic code that i'm using just to get the grasp of it. 正如标题中一样,由于我仍在学习c#,尚未为我点击某些内容,以下是一些我用来掌握它的真正基本代码。

    [TestMethod]
    public void Pass()
    {
        int x = 4;
        Increment(x);
        Assert.AreEqual(5, x);
    }
    void Increment(int num)
    {
        num++;
    }

I know that if i add ref in it will work just fine, however I've seen that using that isn't always the best case. 我知道,如果我在其中添加ref会很好用,但是我已经看到使用它并不总是最好的情况。 What could i do instead of using ref and why? 我可以代替ref做什么,为什么?

  1. Don't mutate state in the caller. 不要改变呼叫者的状态。 Return the new int value as the return value. 返回新的int值作为返回值。 State mutation is to be avoided in general. 通常应避免状态突变。
  2. Continue to use ref if available. 如果可用,请继续使用ref。 Nothing wrong with it except for the state mutation problem. 除了状态突变问题,它没有其他问题。
  3. Use an object on the heap, for example class IntHolder { int MyInt; } 在堆上使用一个对象,例如, class IntHolder { int MyInt; } class IntHolder { int MyInt; } or StrongBox<int> which is built-in. class IntHolder { int MyInt; }或内置的StrongBox<int>

If you tell us more context we can recommend a specific solution. 如果您告诉我们更多背景信息,我们可以推荐一种特定的解决方案。

[TestMethod] public void Pass() {
    int x = 4;
    x = Increment(x);
   Assert.AreEqual(5, x);
 }

int Increment(int num) {return ++num; }

This should work if your set on not using passing by ref. 如果您的设置不使用通过引用传递,这应该可以工作。

Essentially when not passing by ref your giving the called method a copy of the original object. 本质上,当不通过ref传递时,您给被调用的方法一个原始对象的副本。 So your changes to it in Increment won't be reflected on the original (unless like here you return the new value from the method and use it in an assignment). 因此,您对Increment所做的更改将不会反映在原始值上(除非像此处您从方法中返回新值并在分配中使用它)。

When passing by ref your giving the called method a reference to your original object. 当通过ref传递时,给调用的方法一个对原始对象的引用。 In that case any ammendments ARE performed on the original. 在这种情况下,会对原件进行任何修改。

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM