首页 > 解决方案 > 如何创建具有嵌入式字段的结构?

问题描述

我正在互联网上寻找有关这方面的信息,但没有成功。目标是实现一个包含 10 个主题 (sub_1, sub_2... sub_10) 的数据集,每个主题完成 3 种活动 (walk, run, jump) 每次 (trial_1...trial_3) 3 次相对分数。我想访问这些信息,例如:

variable = dataset.sub_1.jump.trial_2.score;

或者至少:

variable = dataset.sub[0].task[2].trial[1].score;

因此,该结构将是一个树形结构。到目前为止,我只实现了一个具有“并行字段”的结构:

struct dataset
{
    public string[] sub;   // 1 to 10 subjects
    public string[] task;  // 1 to 3 tasks
    public string[] trial; // 1 to 3 trials
    public int score;      // the score of the above combination
}

任何的想法?

标签: c#databasestructure

解决方案


using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    public class Trial
    {
        public Trial(int score)
        {
            Score = score;
        }

        public int Score { get; set; }
    }

    public class Task
    {
        public List<Trial> Trials { get; } = new List<Trial>();
    }

    public class Subject
    {
        public Dictionary<string, Task> Tasks { get; } = new Dictionary<string, Task>();

        public Subject()
        {
            Tasks.Add("walk", new Task());
            Tasks.Add("run", new Task());
            Tasks.Add("jump", new Task());
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Subject player1 = new Subject();

            player1.Tasks["run"].Trials.Add(new Trial(score: 3));

            Console.WriteLine(player1.Tasks["run"].Trials[0].Score);
        }
    }
}

可能所有的类都太多了,但也许你想为某天的任务添加一个描述属性或为试用添加一个时间戳。然后就可以了。


推荐阅读