Can I modify a passed method parameter

妖精的绣舞 提交于 2019-12-17 16:44:31

问题


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


回答1:


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.




回答2:


You can change it but the change will not go back to the caller.

If it is a ValueType -> The copy of object is sent

If it is a RefernceType -> Copy of Object reference will be sent by value. In this way properties of the object can be changed but not the reference itself - caller will not see the change anyway.

If it is sent ref -> Reference can be changed.

In C++ you can use const to prevent the change but C# does not have that. This is only to prevent the programmer by mistake try to change it - depending where the const is used.




回答3:


If you want to be able to access the original value, use the second method.

If you don't care about the original value, you can use either one (I'd probably still use the second though).

Either way, you're not going to hurt anybody else's values (even if you re-assign the value, it won't make it back to the caller) in this case.



来源:https://stackoverflow.com/questions/3991022/can-i-modify-a-passed-method-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!