C# string reference type?

前端 未结 10 1203
梦如初夏
梦如初夏 2020-11-22 10:10

I know that \"string\" in C# is a reference type. This is on MSDN. However, this code doesn\'t work as it should then:

class Test
{
    public static void          


        
10条回答
  •  轮回少年
    2020-11-22 10:37

    Here's a good way to think about the difference between value-types, passing-by-value, reference-types, and passing-by-reference:

    A variable is a container.

    A value-type variable contains an instance. A reference-type variable contains a pointer to an instance stored elsewhere.

    Modifying a value-type variable mutates the instance that it contains. Modifying a reference-type variable mutates the instance that it points to.

    Separate reference-type variables can point to the same instance. Therefore, the same instance can be mutated via any variable that points to it.

    A passed-by-value argument is a new container with a new copy of the content. A passed-by-reference argument is the original container with its original content.

    When a value-type argument is passed-by-value: Reassigning the argument's content has no effect outside scope, because the container is unique. Modifying the argument has no effect outside scope, because the instance is an independent copy.

    When a reference-type argument is passed-by-value: Reassigning the argument's content has no effect outside scope, because the container is unique. Modifying the argument's content affects the external scope, because the copied pointer points to a shared instance.

    When any argument is passed-by-reference: Reassigning the argument's content affects the external scope, because the container is shared. Modifying the argument's content affects the external scope, because the content is shared.

    In conclusion:

    A string variable is a reference-type variable. Therefore, it contains a pointer to an instance stored elsewhere. When passed-by-value, its pointer is copied, so modifying a string argument should affect the shared instance. However, a string instance has no mutable properties, so a string argument cannot be modified anyway. When passed-by-reference, the pointer's container is shared, so reassignment will still affect the external scope.

提交回复
热议问题