我可以修改传递方法参数 [英] Can I modify a passed method parameter
问题描述
我的直觉说我不应该做到以下几点。我没有得到任何警告一下吧。
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.
这篇关于我可以修改传递方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!