List passed by ref - help me explain this behaviour

后端 未结 8 2304
名媛妹妹
名媛妹妹 2020-12-02 05:39

Take a look at the following program:

class Test
{
    List myList = new List();

    public void TestMethod()
    {
        myList.Add         


        
8条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-02 06:16

    Use the ref keyword.

    Look at the definitive reference here to understand passing parameters.
    To be specific, look at this, to understand the behavior of the code.

    EDIT: Sort works on the same reference (that is passed by value) and hence the values are ordered. However, assigning a new instance to the parameter won't work because parameter is passed by value, unless you put ref.

    Putting ref lets you change the pointer to the reference to a new instance of List in your case. Without ref, you can work on the existing parameter, but can't make it point to something else.

提交回复
热议问题