// Dictionary.Add 方法使用最后的记录值更新所有先前的记录,但 // 记录的键值是正确的。
// 尝试使用一组简单的代码为 Dictionary 集合创建一个测试床。添加仍会更新所有先前的值。这是代码
namespace DictionaryCollection_test_bed
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DictionaryCollection_test_bed
{
class Program
{
static void Main(string[] args)
{
//Set up Dictionary Clooection and instantiate TaxParcel class
Dictionary<string, TaxParcel> ParcelData = new Dictionary<string, TaxParcel>();
TaxParcel ParcelPair = new TaxParcel();
ParcelPair.ParcelID = "1";
ParcelPair.Owner = "Owner1";
ParcelPair.Address = "Address1";
ParcelData.Add(ParcelPair.ParcelID, ParcelPair);
//this record is correct at this point
//Key ="1", ParcelID = "1", Owner = "Owner1", Address = "Address1"
ParcelPair.ParcelID = "2";
ParcelPair.Owner = "Owner2";
ParcelPair.Address = "Address2";
ParcelData.Add(ParcelPair.ParcelID, ParcelPair);
//Record 1 now has parcel2 values but still with key 1
//Key ="1", ParcelID = "2", Owner = "Owner2", Address = "Address2"
//Record 2 has the correct values for the record
//Key ="2", ParcelID = "2", Owner = "Owner2", Address = "Address2"
}
}
//Class declaration
public class TaxParcel
{
public string ParcelID { get; set; }
public string Owner { get; set; }
public string Address { get; set; }
}
}
您尝试使用字典来存储 TaxParcel 类的多个实例,每个实例都由唯一的 ParcelID 标识。但是您正在重用 ParcelPair 对象来将新条目添加到 ParcelData 字典中。
将 ParcelPair 添加到字典后修改其属性时,您只是修改存储在其中的同一实例。 C# 类是引用类型,因此 ParcelPair 引用内存中的对象。因此,将 ParcelPair 添加到字典后更改它会更改字典引用的对象。
要正确地将多个唯一的 TaxParcel 实例添加到字典中,您需要为要添加的每个地块实例化一个新的 TaxParcel 对象,如下所示:
namespace DictionaryCollection_test_bed
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DictionaryCollection_test_bed
{
class Program
{
static void Main(string[] args)
{
//Set up Dictionary Clooection and instantiate TaxParcel class
Dictionary<string, TaxParcel> ParcelData = new
Dictionary<string, TaxParcel>();
TaxParcel ParcelPair = new TaxParcel();
ParcelPair.ParcelID = "1";
ParcelPair.Owner = "Owner1";
ParcelPair.Address = "Address1";
ParcelData.Add(ParcelPair.ParcelID, ParcelPair);
//this record is correct at this point
//Key ="1", ParcelID = "1", Owner = "Owner1", Address = "Address1"
TaxParcel ParcelPair2 = new TaxParcel();// <Add this and rename ParcelPair to ParcelPair2
ParcelPair2.ParcelID = "2";
ParcelPair2.Owner = "Owner2";
ParcelPair2.Address = "Address2";
ParcelData.Add(ParcelPair.ParcelID, ParcelPair2);
//Key ="2", ParcelID = "2", Owner = "Owner2", Address = "Address2"
// Now they should have the correct values
}
}
//Class declaration
public class TaxParcel
{
public string ParcelID { get; set; }
public string Owner { get; set; }
public string Address { get; set; }
}
}
}