我可以修改传递方法参数

编程入门 行业动态 更新时间:2024-10-23 23:31:46
本文介绍了我可以修改传递方法参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的直觉说我不应该做到以下几点。我没有得到任何警告一下吧。

my gut feeling says I shouldn't do the following. I don't get any warnings about it.

void test(DateTime d) { d = d.AddDays(2); //do some thing with d }

或这更恰当

void test(DateTime d) { DateTime _d = d.AddDays(1); //do some thing with _d }

有关某种原因,我有总是处理就像在第二个例子中传递的参数。 但我不知道这是否是真的nessesry ...也许这只是unnessary代码。

For some reason I have always handled passed parameters like in the second example. But I am not sure if it's really nessesry...maybe it's just unnessary code.

我不打算调用的方法将采用改良值。 任何人有任何意见

I am not thinking that the calling method would be using the modified value. anyone have any opinions

推荐答案

更改为参数的值的是不可见的来电者,除非它是一个 REF 或退出参数。

Changes to the value of a parameter are invisible to the caller, unless it's a ref or out parameter.

这是的不的,如果你更改了一个引用类型对象的情况下的简称的一个参数。例如:

That's not the case if you make a change to an reference type object referred to by a parameter. For example:

public void Foo(StringBuilder b) { // Changes the value of the parameter (b) - not seen by caller b = new StringBuilder(); } public void Bar(StringBuilder b) { // Changes the contents of the StringBuilder referred to by b's value - // this will be seen by the caller b.Append("Hello"); }

最后,如果该参数是按引用传递,变化的是的看出:

public void Baz(ref StringBuilder b) { // This change *will* be seen b = new StringBuilder(); }

有关更多相关信息,请参阅我的文章参数传递。

For more on this, see my article on parameter passing.

更多推荐

我可以修改传递方法参数

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

发布评论

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

>www.elefans.com

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