在方法内修改方法参数或返回结果

编程入门 行业动态 更新时间:2024-10-10 02:14:11
本文介绍了在方法内修改方法参数或返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

What is the difference between

private void DoSomething(int value) { value++; }

private int DoSomething(int value) { return value++; }

当用作其中一个

DoSomething(value);

对比

value = DoSomething(value);

推荐答案

您正在谈论的是传递按引用和按值传递,这在概念上类似于 值类型与引用类型的概念。

You are talking about the difference between passing by reference and passing by value, which is conceptually similar to the idea of value types vs reference types.

如果将值类型传递给方法,则必须使用第二个示例;否则,您只是递增DoSomething()范围内存在的整数。尝试一下:如果执行第一个示例,则在DoSomething()运行之后,int的值将保持不变。

If you pass a value type into the method, you have to use the second example; otherwise you are just incrementing an integer that exists inside the scope of DoSomething(). Try it: if you execute your first example, after DoSomething() has run, the value of your int will be unchanged.

但是,如果您要传递其他内容而不是值类型(例如对象foo),您实际上是传递引用到原始对象。在DoSomething()中对它执行的任何操作也会在该方法之外生效,因为您仍在引用同一对象。

However, if you are passing in something other than a value type (say object foo), you are actually passing a reference to the original object. Anything you do to it inside DoSomething() will take effect outside the method as well, since you are still referring to the same object.

您可以完成自己要执行的操作尝试在第一个示例中编写:

You can accomplish what you're attempting in the first example by writing:

void DoSomething(ref int value)

指示.NET传递对该项的引用,而不管其是否为值类型。

That instructs .NET to pass a reference to the item regardless of whether it is a value type.

请参见 值类型与引用在MSDN上键入 以获取更详细的外观。

See this writeup on Value Types vs Reference Types on MSDN for a more detailed look.

此外,如 zodoz指出了(适当地投票),方法是返回 value ++ 您正在返回然后递增。要返回增加的值,请使用 ++ value 。

Additionally, as zodoz points out (upvote appropriately), by returning value++ you are returning and then incrementing. To return the incremented value, use ++value.

更多推荐

在方法内修改方法参数或返回结果

本文发布于:2023-11-25 21:22:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631397.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   参数

发布评论

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

>www.elefans.com

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