c# - 如何创建具有嵌入式字段的结构?
问题描述
我正在互联网上寻找有关这方面的信息,但没有成功。目标是实现一个包含 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
}
任何的想法?
解决方案
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);
}
}
}
可能所有的类都太多了,但也许你想为某天的任务添加一个描述属性或为试用添加一个时间戳。然后就可以了。
推荐阅读
- python - 识别列表项是否在字符串中
- algorithm - 约束一致的 Delaunay 三角剖分的实际实现
- macos - macOS 上侧边栏的导航问题 (SwiftUI)
- postgresql - JOOQ - 使用表达式更新语句
- vba - vba编译错误:不正确的实现接口
- javascript - 为什么我不能使用 D3 在一个 HTML 页面中显示多个图形?
- python - 从我的脚本中的错误中删除 CSV python 中的行
- mysql - MySQL:改进 SELECT-Statement:为表格中的每个税率选择净额更灵活
- python - 使用泡菜和烧瓶制作待办事项列表
- django - Django 2/3 每次保存模型时只接收一个 post_save 生成的 celery 信号