无法为Dictionary创建“set”访问器

问题描述 投票:1回答:1

我最初在我的代码中遇到问题,我无法将项目“添加”到列表对象。然而,在查看列表对象之后,我意识到它只包含“get”,而不是“set”。所以,我正在尝试创建一个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(); }
}

我尝试包含一个setter,但是我收到以下错误:

无法转换源类型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; }

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

c# set
1个回答
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(){....};
© www.soinside.com 2019 - 2024. All rights reserved.