在List <T>中添加List <DateTime>值

Jaz*_*rix 4 c# datetime list

这可能是一种棘手的问题.基本上我有一个看起来像这样的课:

class Timer
{
    public string boss { get; set; }
    public List<DateTime> spawnTimes { get; set; }
    public TimeSpan Runtime { get; set; }
    public BossPriority priority { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

如您所见,我想在我的对象中添加DateTimes列表.所以我创建了一个如下所示的列表:

List<Timer> bosses = new List<Timer>();
Run Code Online (Sandbox Code Playgroud)

我希望我可以做类似的事情,添加DateTimes:

bosses.Add(new Timer { boss = "Tequatl", priority = BossPriority.HardCore, spanTimes = {  DateTime.ParseExact("07:00 +0000", "hh:mm zzz", CultureInfo.InvariantCulture) } });
Run Code Online (Sandbox Code Playgroud)

不幸的是,这给了我一个"对象引用未设置为对象的实例".错误.

像这样做,也没有区别:(

Timer boss = new Timer();
DateTime t1 = DateTime.ParseExact("07:00 +0000", "hh:mm zzz", CultureInfo.InvariantCulture);
DateTime t2 = DateTime.ParseExact("11:30 +0000", "hh:mm zzz", CultureInfo.InvariantCulture);
boss.spawnTimes.AddRange(new List<DateTime> { t1, t2 });
Run Code Online (Sandbox Code Playgroud)

我真的在每个DateTime上都添加.Add()吗?

Dai*_*Dai 5

您的NRE是由您未初始化的事实引起的Timer.spawnTimes.

如果将类初始化为默认构造函数的一部分,则可以节省输入:

public class Timer {

    public List<DateTime> SpawnTimes { get; private set; }
    ...

    public Timer() {
        this.SpawnTimes = new List<DateTime>();
    }

}
Run Code Online (Sandbox Code Playgroud)

另一种选择是让一个重载的构造函数接受params参数:

public class Timer {

    public List<DateTime> SpawnTimes { get; private set; }
    ...

    public Timer() {
        this.SpawnTimes = new List<DateTime>();
    }

    public Timer(String boss, /*String runtime,*/ BossPriority priority, params String[] spawnTimes) : this() {

        this.Boss = boss;
//      this.Runtime = TimeSpan.Parse( runtime );
        this.Priority = priority;

        foreach(String time in spawnTimes) {

            this.SpawnTimes.Add( DateTime.ParseExact( time, "HH:mm" ) );
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

这在实践中使用如下:

bosses.Add( new Timer("Tequat1", BossPriority.HardCore, "07:00 +0000" ) );
bosses.Add( new Timer("Tequat2", BossPriority.Nightmare, "01:00 +0000", "01:30 +0000" ) );
bosses.Add( new Timer("Tequat3", BossPriority.UltraViolence, "12:00 +0000" ) );
Run Code Online (Sandbox Code Playgroud)

另外:FxCop/StyleCop时间!

  • 类型(如类)应该是 PascalCase
  • 公共成员也应该是PascalCase(与Java不同camelCase)
    • 例如public BossPriority priority应该public BossPriority Priority
  • 收集成员不应通过可变属性暴露(即使用private set而不是set(隐含的公共)
  • 公共收藏成员应该是Collection<T>ReadOnlyCollection<T>代替List<T>T[]