无法为字典创建“设置”访问器

时间:2019-04-11 15:38:33

标签: c# set

最初,我的代码遇到问题,无法将项目“添加”到列表对象。但是,在查看了列表对象之后,我意识到它只包含一个“ 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; }

知道我在做什么错吗?
谢谢

1 个答案:

答案 0 :(得分:1)

我会做这样的事情:

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(){....};