您可以使用字典,但不能使用List<string>!您总是需要完全相同的列表引用才能从Dictionary 访问相应的元素。
而让内部的只是一个Dictionary<string, bool> 用于将一个键映射到一个值。
出于可读性和可维护性的原因,而不是嵌套这些集合类型,我宁愿创建适当的包装类,例如
public class GridCell
{
public Dictionary<string, bool> Properties = new Dictionary<string, bool>();
}
然后由于您提到了网格而不是通过字符串键访问某些字段,我宁愿在实际的“网格”或二维数组中使用它
public GridCell[,] Grid = new GridCell[width, height];
public List<string> GridProperties = new List<string>();
为了初始化它,你会运行一次,例如
for(var i = 0; i < width; i++)
{
for(var j = 0; j < height; j++)
{
var newGridCell = new GridCell();
foreach(var property in GridProperties)
{
newGridCell.properties.Add(property, false);
}
Grid[i, j] = newGridCell;
}
}
然后您可以访问任何属性,例如
var hasProperty = Grid[2,2].Properties[propertyName];
Grid[2,2].Properties[propertyName] = true;
为了一次设置多个属性而实现一个类似的方法
public class GridCell
{
public Dictionary<string, bool> Properties = new Dictionary<string, bool>();
public void SetProperties(List<string> properties, bool value)
{
foreach(var property in properties)
{
// Either updates the entry if it exists already
// or adds a new entry for this key
Properties[property] = value;
}
}
}
然后在网格类中去
public void SetProperties(int gridX, int gridY, List<string> properties, bool value)
{
// creates the new field if it didn't exist so far
if(Grid[gridX, gridX] == null)) Grid[gridX, gridY] = new GridCell();
Grid[gridX, gridY].SetProperties(properties, value);
}
当然,你仍然可以只使用字典来做同样的事情,就像在内部字典之前一样不使用List<string>但只有string作为键
public Dictionary<string, Dictionary<string, bool>> Grid = new Dictionary<string, Dictionary<string, bool>>();
然后在相应地初始化它之后,您可以访问一个特定的值,例如
var hasProperty = Grid[indexName][propertyName];
Grid[indexName][propertyName] = true;
为了一次设置多个值,您应该实现自己的方法,例如
public void SetProperties(string indexName, List<string> properties, bool value)
{
// creates the new field if it didn't exist so far
if(!Grid.ContainsKey(indexName)) Grid[indexName] = new Dictionary<string, bool>();
foreach(var property in properties)
{
// This either updates an existing property entry
// or creates a new one if it didn't exist so far
Grid[indexName][property] = value;
}
}
我更喜欢顶部的解决方案以获得更好的可维护性。您可以轻松地在GridCell 类中实现更多方法,或者更改和扩展现有方法,而不会过多影响外部的任何内容。您还可以轻松地将与网格相关的内容分离(解耦)到一个额外的类中,而无需例如使用太多方法使MonoBehaviour 组件混乱。
使用第二种方法,您将终止于一个超级强大的类,该类在这个嵌套的Dictionary 内完成所有工作。