C# Object property modified in the called function

2019-04-16 20:51发布

I defined a simple class with the following definition. In this sample, I defined a simple class with a single string parameter. Then I instantiated this class and assigned a value to the parameter. I passed that instance to another function without specifying "ref" keyword. It means it should be passed by value instead of reference. But what I don't understand is the reason that the output displays "Second Modification" value as a result instead of "First Modification".

UPDATE 1:

I think my question was confusing. I know how "ref" and "pass by reference" working. I need to know why when I "pass by value", run-time still changes the value of the original instance. By the way, I couldn't find my answer in the proposed links.

UPDATE 2:

I asked this question two years ago. Now I understand all properties of an object (instance of a class) are reference type. It means when I pass an instance of a class to another method, they all behave as a reference to original member of the class.


public class MyClass
{
    public String TestProperty { get; set; }
}

public class TestClass
{
    public TestClass()
    {
        var myClass = new MyClass();
        myClass.TestProperty = "First Modification";
        MyFunction(myClass);
        Console.WriteLine(myClass.TestProperty); // Output: "Second Modification"
    }
    void MyFunction(MyClass myClass)
    {
        myClass.TestProperty = "Second Modification";
    }
}

2条回答
Lonely孤独者°
2楼-- · 2019-04-16 21:32

That is the expected behavior. What ref would allow you to do is create a new object in MyFunction and assign it to the myClass parameter and have the new object available outside the method.

   void MyFunction(ref MyClass myClass)
   {
     myClass = new MyClass(); //this new instance will be accessible outside the current method
   }

Have a look at http://msdn.microsoft.com/en-us/library/14akc2c7.aspx for more details.

查看更多
叛逆
3楼-- · 2019-04-16 21:46

You can change the object passed to the method, but you can't change the reference itself without the ref keyword

public class MyClass
{
    public String TestProperty { get; set; }
}

public class TestClass
{
    public TestClass()
    {
        var myClass = new MyClass();
        myClass.TestProperty = "First Modification";

        MyFunction(myClass);
        Console.WriteLine(myClass.TestProperty); // Output: "First Modification"

        MyRefFunction(ref myClass);
        Console.WriteLine(myClass.TestProperty); // Output: "Third Modification"
    }
    void MyFunction(MyClass myClass)
    {
        myClass = new MyClass() { TestProperty = "Second Modification"};
    }

    void MyRefFunction (ref MyClass myClass)
    {
        myClass = new MyClass() { TestProperty = "Third Modification"};
    }
}

If you want to prevent the property being changed, you can make the setter non-public:

public String TestProperty { get; private set; }
查看更多
登录 后发表回答