在方法内修改方法参数或返回结果 [英] Modify method parameter within method or return result

查看:84
本文介绍了在方法内修改方法参数或返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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.

这篇关于在方法内修改方法参数或返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆