我有一个类似的类
public class Model
{
public TimeSpan Time1 {get; set;}
public TimeSpan Time2 { get; set; }
public TimeSpan Time3 { get; set; }
public TimeSpan Time4 { get; set; }
}
现在让我们想象一下,我必须在运行时填充时间,然后计算出时间 1 和时间 2 之间的剩余时间,然后在时间过去后找到时间 2 和时间 3 之间的剩余时间,依此类推。但是,我需要考虑现在是几点。
例如:
现在是下午 1:00
时间 1=凌晨 5:00 时间 2 = 中午 12:00 时间 3= 下午 4:00 时间 4 = 下午 6:00
所以由于时间是下午 1:00,我需要找出时间 2 和时间 3 之间的差异
现在有没有比反射更聪明的方法来确定这一点?我应该在类里面添加一些东西吗
最佳答案
如果你需要保留你的类的现有结构,你可以添加一个方法来枚举时间:
public class Model
{
public TimeSpan Time1 {get; set;}
public TimeSpan Time2 { get; set; }
public TimeSpan Time3 { get; set; }
public TimeSpan Time4 { get; set; }
public IEnumerable<TimeSpan> GetTimes()
{
yield return Time1;
yield return Time2;
yield return Time3;
yield return Time4;
}
}
然后像这样使用它:
foreach (TimeSpan time in model.GetTimes())
{
// use the TimeSpan
}
关于c# - 在 C# 中枚举类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2520542/