What do ref, val and out mean on method parameters?

后端 未结 4 1676
时光说笑
时光说笑 2020-12-01 16:01

I\'m looking for a clear, concise and accurate answer.

Ideally as the actual answer, although links to good explanations welcome.

This also applies to VB.N

4条回答
  •  清歌不尽
    2020-12-01 16:33

    out means that the parameter will be initialised by the method:

    int result; //not initialised
    
    if( int.TryParse( "123", out result ) )
       //result is now 123
    else
       //if TryParse failed result has still be 
       // initialised to its default value (0)
    

    ref will force the underlying reference to be passed:

    void ChangeMyClass1( MyClass input ) {
       input.MyProperty = "changed by 1";
       input = null;
       //can't see input anymore ... 
       // I've only nulled my local scope's reference
    }
    
    void ChangeMyClass2( ref MyClass input ) {
       input.MyProperty = "changed by 2";
       input = null;
       //the passed reference is now null too.
    }
    
    MyClass tester = new MyClass { MyProperty = "initial value" };
    
    ChangeMyClass1( tester );
    // now tester.MyProperty is "changed by 1"
    
    ChangeMyClass2( ref tester );
    // now tester is null
    

提交回复
热议问题