开发者

Why do these values change like the objects were passed by reference if I set the properties?

Program:

  class Program
  {
    class class1
    {
      public string Name { get; set; }
      public int Value { get; set; }
    }

    class class2
    {
      public string Name { get; set; }
      public int Value { get; set; }
    }

    static void Main(string[] args)
    {
      var Source = new class1() { Name = "Source", Value = 1 };
      var Target = new class2() { Name = "Target", Value = 2 };

      setValue(Source, Target);
      Console.WriteLine(string.Format("Source - Name:{0} Value:{1}", Source.Name,Source.Value));
      Console.WriteLine(string.Format("Target - Name:{0} Value:{1}",Target.Name, Target.Value));
    }

    private static void setValue(object Source, object Target)开发者_如何学C
    {

      Target  = Source;
    }    
  }  

When this runs I get(which I expected):

Source - Name:Source Value:1
Target - Name:Target Value:2

But when I change the setValue method to:

private static void setValue(object Source, object Target)
{
  var source = Source as class1;
  var target = Target as class2;

  target.Name = source.Name;
  target.Value = source.Value;
}  

I get:

Source - Name:Source Value:1
Target - Name:Source Value:1


This line:

Target  = Source;

Is just copying the value of Source into the variable Target.

That value is just a reference - and Target is effectively just a local variable, as it's a normal parameter.

In your other code:

var source = Source as class1;
var target = Target as class2;

target.Name = source.Name;
target.Value = source.Value;

That's setting the data within the objects which are referred to by the parameters. Think about it like this. Imagine you give someone a piece of paper with an address on, and they go to that address and painting the house red. Later you visit the house yourself, and you see that it's red.

Now compare that with your first example - that's like giving someone a piece of paper, and them crossing out the address and writing the address of a red house onto it. You don't see this - you just gave them the piece of paper and let them get on with it. So when you go to the original address, you don't see a red house, because it hasn't changed.

I have two articles which may help you to understand the concepts involved:

  • Parameter passing
  • Reference types and value types


I'm failing to see the issue here...

C# passes the reference to the objects by value to the setValue method. Because of this, you can't change the reference of the object. ie: you can't create or reassign the whole object.

However, because you have the reference to the object in setValue you can absolutely change it's data.


Try this,

private static void setValue(object Source,ref object Target) {

  Target  = Source;
}    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜