这可能有点棘手。基本上我有一个看起来像这样的类:
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/