我最初在代码中遇到了一个问题,即我无法将项目"添加"到列表对象。 然而,在查看列表对象后,我意识到它只包含一个"get",而不是一个"集合"。 所以,我正在尝试创建一个 set 访问器,但我遇到了问题:这是我将项目添加到列表对象的原始代码。 目前,未添加任何内容:
ClientCompany clientCompany = new ClientCompany();
LocationData urlData = new LocationData();
Location location = urlData.LocationGet(1129); //hardcoded 1129 in for now
clientCompany.Locations.Add(location); //"location" is NOT null, however nothing gets added to Locations object
return clientCompany; //clientCompany.Locations.Count = 0 (it should equal 1)
这是我遇到问题的 ClientCompany 类的当前部分:
public Dictionary<int, Location> LocationsDict { get; set; }
// List Properties
public List<Location> Locations
{
get { return LocationsDict.Values.ToList(); }
}
我尝试包括一个二传手,但我收到以下错误:
无法转换源类型
Systems.Collections.Generic.List<MyCompany.MVC.MyProject.Models.ClientCompany.Location>' to target type 'Systems.Collections.Generic.Dictionary<int, MyCompany.MVC.MyProject.Models.ClientCompany.Location>
get { return LocationsDict.Values.ToList(); }
set { LocationsDict = value; }
知道我做错了什么吗?
谢谢
我会做这样的事情:
private Dictionary<int, Location> LocationsDict = new Dictionary<int, Location>();
public void Set(int key, Location value)
{
if (LocationsDict.ContainsKey(key))
LocationsDict[key] = value;
else
LocationsDict.Add(key, value);
}
public Location Get(int key)
{
return LocationsDict.ContainsKey(key) ? LocationsDict[key] : null; }
}
或者更好的(我认为(您可以使用索引器:
public class MyClass
{
private readonly IDictionary<int, Location> LocationsDict = new Dictionary<int, Location>();
public Location this[int key]
{
get { return LocationsDict.ContainsKey(key) ? LocationsDict[key] : null; }
set
{
if (LocationsDict.ContainsKey(key))
LocationsDict[key] = value;
else
LocationsDict.Add(key, value);
}
}
}
var gotest = new MyClass();
gotest[0] = new Location(){....};