c# - 在 C# 中枚举类属性

标签 c# linq silverlight reflection

我有一个类似的类

 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/

相关文章:

c# - 在linq中加入两个数据表作为父子

带投影的 Linq groupby 查询

c# - 什么是 List<T> 类?

silverlight - 如何确定是否在 Silverlight 应用程序中切换了 Caps Lock?

.net - 在 F# 中使用 LINQ?

Silverlight 2 拖放教程

c# - 如何索引字符串数组

c# - 如何从音频文件中获取 musicbrainz 轨道信息

c# - 控制台应用程序中的全局热键

c# - 使用 Flurl 发布多个标题