gpt4 book ai didi

c# - 在 List 中添加 List

转载 作者:太空狗 更新时间:2023-10-30 00:07:30 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com