Skip to main content
 首页 » 编程设计

c#之如何在字典中存储任意数量的任意类型的数组

2024年02月20日12www_RR

我正在尝试构建一个数据结构,可以通过我正在运行的一组不同测试的跟踪结果来存储试验。测试全部由许多轨迹组成,但我想要保存和以后使用的一些信息对于不同的测试是不同的。例如,TestA 的结果可能如下所示:

Trial(int)   WasResponseCorrect(bool)   WhichButtonWasPressed(string)   SimulusLevel(double) 
 
   1                  false                         "Up"                         3.5 
   2                  true                          "Left"                       6.5 

其中 TestB 可能有不同类型的结果字段:

Trial(int)    WasResponseCorrect(bool)    ColorPresented(string)    LetterPresented(char)     LetterGuessed(Char) 
  1                     false                      green                     G                        C 
 
  2                     false                      blue                      H                        F 

我正在考虑创建一个字典,其中字段名称作为键(例如 WasResponseCorrect),字段值数组作为 dic 的值。我不知道该怎么做。也许有更好的方法来存储信息,但我想不出该怎么做。我正在使用 .net(VB 和 C#),但如果您知道其他语言的示例,我认为我可以理解和转换大多数代码。谢谢!

请您参考如下方法:

在不了解您的需求(例如,您将如何存储数据)的情况下,多态性似乎就是您要寻找的东西。也就是说,您有一个父类(super class)(称为 Trial)和代表特定试验类型的子类。例如:

public class Trial { 
    public int Id { get; set; } 
    public bool WasResponseCorrect { get; set; } // if this is in every type of trial 
    // anything else that is common to ALL trial types 
} 
 
public class TrialA : Trial { 
    public string WhichButtonWasPressed { get; set; } 
    public double SimulusLevel { get; set; } 
} 
 
public class TrialB : Trial { 
    public string ColorPresented { get; set; } 
    public char LetterPresented { get; set; } 
    public char LetterGuessed { get; set; } 
} 

这样你就可以获得一个 Trial 对象的列表,但是这些对象的实际运行时类型可以是 TrialA 或 TrialB。