Are ILists passed by value?

后端 未结 6 1197
谎友^
谎友^ 2020-12-16 05:26

Passing Value Type parameters to functions in c# is by value unless you use the ref or out keyword on the parameter. But does this also apply to Reference Types?

Sp

6条回答
  •  离开以前
    2020-12-16 05:52

    You're not alone; this confuses a lot of people.

    Here's how I like to think of it.

    A variable is a storage location.

    A variable can store something of a particular type.

    There are two kinds of types: value types and reference types.

    The value of a variable of reference type is a reference to an object of that type.

    The value of a variable of value type is an object of that type.

    A formal parameter is a kind of variable.

    There are three kinds of formal parameters: value parameters, ref parameters, and out parameters.

    When you use a variable as an argument corresponding to a value parameter, the value of the variable is copied into the storage associated with the formal parameter. If the variable is of value type, then a copy of the value is made. If the variable is of reference type, then a copy of the reference is made, and the two variables now refer to the same object. Either way, a copy of the value of the variable is made.

    When you use a variable as an argument corresponding to an out or ref parameter the parameter becomes an alias for the variable. When you say:

    void M(ref int x) { ...}
    ...
    int y = 123;
    M(ref y);
    

    what you are saying is "x and y now are the same variable". They both refer to the same storage location.

    I find that much easier to comprehend than thinking about how the alias is actually implemented -- by passing the managed address of the variable to the formal parameter.

    Is that clear?

提交回复
热议问题