C# string reference type?

前端 未结 10 1201
梦如初夏
梦如初夏 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:22

    Above answers are helpful, I'd just like to add an example that I think is demonstrating clearly what happens when we pass parameter without the ref keyword, even when that parameter is a reference type:

    MyClass c = new MyClass(); c.MyProperty = "foo";
    
    CNull(c); // only a copy of the reference is sent 
    Console.WriteLine(c.MyProperty); // still foo, we only made the copy null
    CPropertyChange(c); 
    Console.WriteLine(c.MyProperty); // bar
    
    
    private void CNull(MyClass c2)
            {          
                c2 = null;
            }
    private void CPropertyChange(MyClass c2) 
            {
                c2.MyProperty = "bar"; // c2 is a copy, but it refers to the same object that c does (on heap) and modified property would appear on c.MyProperty as well.
            }
    

提交回复
热议问题