Change value inside an (void) extension method

前端 未结 6 1019
心在旅途
心在旅途 2021-02-12 23:28

So I have this mock extension method which change a value to another value:

public static void ChangeValue(this int value, int valueToChange)
{
    value = value         


        
6条回答
  •  清歌不尽
    2021-02-12 23:57

    Because int is value type, so it copied by value when you pass it inside a function.

    To see the changes outside of the function rewrite it like:

    public static int ChangeValue(this int value, int valueToChange)
    {
        //DO SOMETHING ;
    
        return _value_; //RETURN COMPUTED VALUE 
    }
    

    It would be possible to do using ref keyowrd, but it can not be applied on parameter with this, so in your case, just return resulting value.

提交回复
热议问题