Can I modify a passed method parameter

后端 未结 3 1974
逝去的感伤
逝去的感伤 2020-12-06 18:07

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


        
3条回答
  •  渐次进展
    2020-12-06 18:12

    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.

提交回复
热议问题