[英]What is the best way to exchange references?
What is the best way to exchange references in C#? 在C#中交换引用的最佳方法是什么?
Why my static method Exchange
doesn't work? 为什么我的静态方法Exchange
不起作用? But the code in Main works. 但是Main中的代码有效。
class Person
{
public Person(int money)
{
Money = money;
}
public int Money { get; set; }
public static void Exchange(Person p1, Person p2)
{
Person newPerson = p1;
p1 = p2;
p2 = newPerson;
}
public object Clone()
{
return new Person( Money);
}
}
class Program
{
static void Main(string[] args)
{
Person p1 = new Person(100);
Person p2=new Person(200);
Person newPerson = p1;
p1 = p2;
p2 = newPerson;
Console.WriteLine(p1.Money);
Console.WriteLine(p2.Money);
Console.ReadKey();
}
}
You need the ref
keyword: 您需要ref
关键字:
public static void Exchange(ref Person p1, ref Person p2)
called thusly: 因此称:
Person.Exchange(ref person1, ref person2);
The reason is that without ref
, p1
and p2
are copies of the reference . 原因是没有ref
, p1
和p2
是参考的副本。 That's not to say they are copies of the object, but copies of the reference to that object. 并不是说它们是对象的副本,而是对象的引用的副本。
See the docs on the ref keyword for more information. 有关更多信息,请参见ref关键字上的文档。
That's because in C# both value and reference types are passed by value ie copy is passed.We need to tell explicitly where we need to pass them by reference. 这是因为在C#中,值和引用类型都通过值传递,即传递了复制。我们需要明确告知需要在何处通过引用传递它们。
For reference types a copy of reference is passed. 对于引用类型,将传递引用副本。 So inside your method swapping them does not affect the original object reference out side the calling method, because the variables outside the calling method have different copy of reference than of those inside the method though they both point to the same object and changing the state from any of them will affect the object. 因此,在您的方法内部交换它们不会影响调用方法外部的原始对象引用,因为调用方法外部的变量与方法内部的变量具有不同的引用副本,尽管它们都指向同一对象并更改状态。它们中的任何一个都会影响对象。
As @John pointed use ref
to pass the references by reference for that. 正如@John指出的那样,使用ref
通过引用传递引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.