Setting a type reference type to null doesn't affect copied type?

后端 未结 5 1662
天涯浪人
天涯浪人 2020-12-09 12:57

Why does this produce \"0\" ?

object a = 0;
object b = a;
a = null;
Console.WriteLine(b.ToString()); // Produces \"0\"
Console.Read();

Does

5条回答
  •  执念已碎
    2020-12-09 13:49

    You want to know where the cookies are. You have a piece of paper, labelled "A". On the paper is written in pencil "123 Sesame Street".

    The paper is not a cookie. The address is not a cookie. The paper contains a reference to an address which contains the cookie.

    You obtain a second piece of paper, labelled "B". On that piece of paper, you make a copy of the contents of "A". Now you have two pieces of paper, both say "123 Sesame Street". Both tell you where the cookies are.

    You take piece of paper "A" and erase it. "A" no longer refers to the location of the cookies. B still does.

    You are assuming that saying "b = a" means to write on B "for the location of the cookies, please consult paper A". But that is not what "b = a" means in C#; it means make a copy of the reference, not make an alias of the reference.

    In C# to make an alias of the reference you use the "ref" keyword, confusingly enough:

    void M(ref object b)
    {
        b = null;
    }
    ...
    object a = 0;
    M(ref a);
    // "b" now becomes an alias for "a"; when "b" is nulled out, so is "a" because they are the same variable with two different names.
    

    In C# you can only do this when calling a method that takes a ref parameter like this. The feature you want is not supported in C#, though we have considered supporting it:

    object a = 0;
    ref object b = ref a;
    a = null; // b and a are aliases for the same variable now.
    

    Do you have a compelling need for this feature? If you do, please let me know what it is. That will help us prioritize whether or not the feature is worth doing in a hypothetical future version of C#.

    UPDATE: It got done! This feature was added to C# 7.

提交回复
热议问题