C# 奇数列表行为

标签 c# list pointers

这可能是一个有点菜鸟的问题,但我似乎根本找不到有关此行为的任何信息。

代码如下:

class Cars
{
    public int year = 0;
    public string make = " ";
    public string model = " ";

    public Cars()
    {
    }

    public Cars(int tYear, string tMake, string tModel)
    {
        year = tYear;
        make = tMake;
        model = tModel;
    }

    public string ConvertToString()
    {
        return year.ToString() + make + model;
    }
}

class Program
{
    Cars oneCar = new Cars();
    List<Cars> manyCars = new List<Cars>();

    public void Init()
    {
        manyCars.Add(new Cars(1993, "Nissan", "240SX"));
        manyCars.Add(new Cars(2001, "Isuzu", "Rodeo"));
        manyCars.Add(new Cars(2010, "Ford", "F150"));

        oneCar = manyCars[2];
        oneCar.model = "Pinto";

        for (int i = 0; i < manyCars.Count(); i++)
            Console.WriteLine(manyCars[i].ConvertToString());

        Console.WriteLine(oneCar.ConvertToString());
    }

    static void Main(string[] args)
    {
        Program prg1 = new Program();
        prg1.Init();
    }
}

输出是这样的:

1993Nissan240SX

2001IsuzuRodeo

2010FordPinto

2010FordPinto

为什么第三行读的是 Pinto 而不是 F150?它似乎将 oneCar 变量设置为指针或其他东西。如何避免这种情况?我认为这就是“new”关键字的作用。

在此先感谢您的帮助。

最佳答案

因为Cars是一个对象,而对象在C#中是Reference Types

当你调用这行代码时:

oneCar = manyCars[2];

您正在将 oneCar 指向 manyCars[2] 的内存位置。他们引用同一个对象。更新 oneCar 也会更新 manyCars[2]

This link有一篇关于引用和值类型的好文章。

关于C# 奇数列表行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12699214/

相关文章:

pointers - 如何在golang中通过引用传递struct类型的接口(interface)?

c# - Entity Framework 上的多个 .Where() 子句可查询

c# - 在 C# .NET 中,如何读取具有基于 ascii 的专有编码的文本文件

ios - 从 'CGFloat *' 分配给 'float *'(又名 'int')的指针转换不兼容整数

python - 基于数字模式的增量列表

python - 拆分列表中的字符串以查找和替换 python 中的元素

c++ - 使用数组的段错误

c# - 计算 FFT 相关系数

c# - C# 中 Cmd 命令中的 FFmpeg 完成后的事件

python - 根据另一个具有不完整值的较短列表对列表进行排序