Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

c# - 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
 }

or is this more proper

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");
}

Finally, if the parameter is passed by reference, the change is seen:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...