对于在c#中传递ref / value感到困惑(Confused about passing by ref/value in c#)

编程入门 行业动态 更新时间:2024-10-28 13:29:17
对于在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.

更多推荐

本文发布于:2023-08-02 16:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1378653.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:困惑   ref   passing   Confused

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!