【问题标题】:Creating multiple list in C# for Unity在 C# 中为 Unity 创建多个列表
【发布时间】:2020-10-25 07:15:53
【问题描述】:

尝试在c#中创建一个可以统一从json文件中获取数据的嵌套列表 它目前给我这个错误

error CS1061: 'List<GameHandler.MyCard>' does not contain a definition for 'decision' and no accessible extension method 'decision' accepting a first argument of type 'List<GameHandler.MyCard>' could be found

我想访问 MyDecision 列表中的结果 1 数组,但我只能访问到

void Start()
    {
        CardData cardData = new CardData();
        cardData.card.decision.outcome1 = new int[] { 1, 2, 3 };   
     }

    [Serializable]
    private class CardData
    {
        public List<MyCard> card;
    }

    [Serializable]
    private class MyCard
    {
        public string[] speech;
        public List<MyDecision> decision;
    }

    [Serializable]
    private class MyDecision
    {
        public int[] outcome1;
        public int[] outcome2;
    }

这是我想要访问的 JSON 文件的内容

{
  "CardData" : [
    { "Speech" : ["Hi World."],
      "Decision":[
        {
        "Outcome1":[1,0,0],
        "Outcome2":[0,1,0]
        }
      ]
    },{
      "Speech": ["Hello","World"],
      "Decision":[
        {
        "Outcome1":[1,1,0],
        "Outcome2":[0,1,1]
        }
      ]
    }
  ]
}

【问题讨论】:

  • cardData.card 是一个数组,您正在尝试访问该数组的一项。你需要使用类似的东西:cardData.card[0].decision[0].ourcome1 = new int[] { 1, 2, 3 };
  • "嵌套 List"在哪里?
  • 我强烈建议使用一些命名约定来从其他类型字段/属性中识别列表和数组。示例:使用复数(cardsdecisions)。

标签: c# json unity3d


【解决方案1】:

因为这些是您无法以您尝试的方式访问它们的列表。有几个选项,一个是你可以使用递归方法调用,就像这个问题中的那样:Iterate through nested list with many layers

我将使用的路线是使用 ForEach 遍历列表:

cardData
  .card.ForEach(card => 
    card.decision.ForEach((decision) =>
     {
       decision.outcome1 = new int[] { 1, 2, 3 };
      })
    );

这可能有一些陷阱,您可能想要添加一些错误检查,但它似乎对我来说没问题。

你也应该听一下 Pac0,命名是代码可读性的重要组成部分,所以当它是一个列表时,将名称作为单数会让人感到困惑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 2023-01-02
    • 1970-01-01
    相关资源
    最近更新 更多