c# - 在 List<T> 中添加 List<DateTime> 值

标签 c# list datetime

这可能有点棘手。基本上我有一个看起来像这样的类:

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

}

如您所见,我想在我的对象中添加一个日期时间列表。所以我创建了一个如下所示的列表:

List<Timer> bosses = new List<Timer>();

我希望我可以做类似的事情,添加日期时间:

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

不幸的是,这给了我一个“未设置到对象实例的对象引用”。错误。

这样做,也没有什么区别:(

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 });

我真的在每个日期时间都执行 do.Add() 吗?

最佳答案

你的 NRE 是因为你没有初始化 Timer.spawnTimes .

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

public class Timer {

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

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

}

另一个选择是有一个重载的构造函数来接受 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" ) );
        }

    }
}

这在实践中是这样使用的:

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" ) );

另外:FxCop/StyleCop 时间!

  • 类型(如类)应该是 PascalCase
  • 公共(public)成员也应该是PascalCase (不像在 Java 中它们是 camelCase )
    • 例如public BossPriority priority应该是 public BossPriority Priority
  • 集合成员不应通过可变属性公开(即使用 private set 而不是 set(隐含公开)
  • 公共(public)收藏成员应该是Collection<T>ReadOnlyCollection<T>而不是 List<T>T[]

关于c# - 在 List<T> 中添加 List<DateTime> 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24566330/

相关文章:

javascript - 在 dd/mm/yyyy hh :mm:ss format 中转换日期对象

datetime - 如何计算给定月份的周末数(Carbon Object)?

c# - 处理 Task.Run 中的异常

python - python 中的变异列表

c# - 提供字符串字段时如何正确实现 IWebPartField.Schema

python - 列表理解与某种循环相互依赖?

Python:创建/写入文件直到循环结束

javascript - chrome 中 js 日期对象中奇怪的秒偏移

c# - 如何在 Visual Studio 测试资源管理器中修复 "The active test run was aborted"?

c# - 如何在 Serilog JsonFormatter 输出中包含 "Message"和 "MessageTemplate"?