对于在c#中传递ref / value感到困惑(Confused about passing by ref/value in c#)
正如标题中的东西还没有点击给我,因为我还在学习c#,以下是一些非常基本的代码,我只是用它来掌握它。
[TestMethod] public void Pass() { int x = 4; Increment(x); Assert.AreEqual(5, x); } void Increment(int num) { num++; }我知道,如果我加入裁判会工作得很好,但我已经看到,使用它并不总是最好的情况。 我可以做什么,而不是使用ref,为什么?
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.
[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. What could i do instead of using ref and why?
最满意答案
不要在调用者中改变状态。 返回新的int值作为返回值。 一般来说应避免状态突变。 如果可用,继续使用ref。 除了状态突变问题之外没什么错。 在堆上使用对象,例如class IntHolder { int MyInt; } class IntHolder { int MyInt; }或内置的StrongBox<int> 。如果你告诉我们更多的背景,我们可以推荐一个特定的解
Don't mutate state in the caller. Return the new int value as the return value. State mutation is to be avoided in general. Continue to use ref if available. Nothing wrong with it except for the state mutation problem. Use an object on the heap, for example class IntHolder { int MyInt; } or StrongBox<int> which is built-in.If you tell us more context we can recommend a specific solution.
更多推荐
发布评论