我知道这两个对象指向同一个引用,但我不希望出现这种情况,所以我对如何防止一个对象更改另一个对象感到有些困惑。例如,我是否需要声明一个带新的 Car 对象Car car2 = new Car();
?当我这样做时,resharper 告诉我这是不必要的。这是我的代码:
void Main()
{
Car car = new Car { Color = "Blue"};
Console.WriteLine(car.Color);
//Do I need Car car2 = new Car();
//car2 = car; //Confused.
Car car2 = car;
Console.WriteLine(car2.Color);
car = Format(car);
Console.WriteLine(car.Color);
Console.WriteLine(car2.Color); //How can I prevent car2 from changing color?
}
// Define other methods and classes here
public class Car
{
public string Color {get;set;}
}
public static Car Format(Car car)
{
car.Color = "Red";
return car;
}
var car2= new Car();
car2 = car;
car = Format(car); //This changes car and car2