我正在尝试指定 myObject
映射以使用它们的 ID(自动排序)到达我的对象,我创建了 List<T>
每一个
编辑:(世界、城市、...)这些对象具有 ComponentID 变量。
public enum ComponentType : byte
{
Effect,
Building,
City,
Region,
Country,
World
}
public static class ComponentMap
{
public static List<World> Worlds = new List<World>();
public static List<Country> Countries = new List<Country>();
public static List<Region> Regions = new List<Region>();
public static List<City> Cities = new List<City>();
public static List<Building> Buildings = new List<Building>();
public static List<Effect> Effects = new List<Effect>();
public static ArrayList Map = new ArrayList() {
Effects,
Buildings,
Cities,
Regions,
Countries,
Worlds
};
}
在这里,我正在使用该方法检查我的对象。
private bool CheckExist()
{
ComponentType type = ComponentType.Country;
ushort compId = 12;
return ((List<object>)(ComponentMap.Map[(byte)type]))[compId] == null ? false : true;
}
如你所见,我正在转换 (ComponentMap.Map[(byte)type]) => List(object)
因为,我不能使用 Map
的变量为 List
,它说“它是一个对象而不是列表”。
这个方法正常还是垃圾?如果您有更好的解决方案,请说明。
最佳答案
对于映射,我建议使用内置的字典和集合,它会更快并且更易读(我想你的实体中有 Id
属性):
public static class ComponentMap
{
public static List<World> Worlds = new List<World>();
public static List<Country> Countries = new List<Country>();
public static List<Region> Regions = new List<Region>();
public static List<City> Cities = new List<City>();
public static List<Building> Buildings = new List<Building>();
public static List<Effect> Effects = new List<Effect>();
public static IDictionary<ComponentType, ISet<int>> Map = new Dictionary<ComponentType, ISet<int>>() {
[ComponentType.Effect] = new HashSet<int>(Effects.Select(e => e.Id)),
// etc
};
}
private bool CheckExist()
{
ComponentType type = ComponentType.Country;
ushort compId = 12;
return ComponentMap.Map[type].Contains(compId);
}
如果您想保留对实体的引用,您可以使用 C# 7 元组功能执行以下字典操作:
public static class ComponentMap
{
public static List<World> Worlds = new List<World>();
public static List<Country> Countries = new List<Country>();
public static List<Region> Regions = new List<Region>();
public static List<City> Cities = new List<City>();
public static List<Building> Buildings = new List<Building>();
public static List<Effect> Effects = new List<Effect>();
public static IDictionary<(ComponentType, int), object> Map;
static ComponentMap()
{
var keyValuePars = Worlds
.Select(w => new KeyValuePair<(ComponentType, int), object>((ComponentType.World, w.Id), w)))
.Concat(); // add other items in concats
Map = new Dictionary<(ComponentType, int), object>(keyValuePars);
}
}
private bool CheckExist()
{
ComponentType type = ComponentType.Country;
ushort compId = 12;
return ComponentMap.Map.ContainsKey((type, compId));
}
关于c# - 从 ArrayList 获取变量的好方法包括不同类型的列表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55429284/