如何动态访问所有孩子的?



我有一些产品的json,按类别排序,例如:

{
  "Shoes": [
    { "title": "Product One", "price": 100 ... },
    ....
  ],
  "Hats": [
    { "title": "Product 23", "price": 12.2 ... },
    ...
  ]
}

然后,像这样加载它:

保存到 StreamingAssets/products.json。

public class Products {
    public List<Shoes> Shoes;
    public List<Hats> Hats;
    public static Products CreateFromJSON(string json) {
        string filePath = Path.Combine(Application.streamingAssetsPath, "products.json");
        if (File.Exists(filePath)) {
            string dataAsJson = File.ReadAllText(filePath);
            Products p = JsonUtility.FromJson<Products>(dataAsJson);
            return p;
        }
        Debug.Log("Missing JSON file: " + filePath);
        return null;
    }
}

public class Shoes: Model { }
public class Hats: Model { }
public class Model {
    public string title;
    public int price;
    public string sprite;
    ...
}

这工作正常,加载/解析...,但是

我想动态访问产品,以便能够遍历Products,在循环Products[nameOfsubCategory][0].titleforeach这样的东西。

目前实施工作Products.Shoes[0].title但这不是好的做法,也没有意义。

看看 Linq:你可以做一些像products.Where(p=>p.price>100)和很多其他事情的事情。

最新更新