c# – 任何人都可以简化这个算法吗?

c# – 任何人都可以简化这个算法吗?,第1张

概述基本上我只想检查一个时间段是否与另一个时间段重叠. 空结束日期意味着直到无穷大.有人可以缩短这个,因为它很难阅读.干杯 public class TimePeriod { public DateTime StartDate { get; set; } public DateTime? EndDate { get; set; } public 基本上我只想检查一个时间段是否与另一个时间段重叠.
空结束日期意味着直到无穷大.有人可以缩短这个,因为它很难阅读.干杯
public class TimePeriod    {        public DateTime StartDate { get; set; }        public DateTime? EndDate { get; set; }        public bool Overlaps(TimePeriod other)        {            // Means it overlaps            if (other.StartDate == this.StartDate                || other.EndDate == this.StartDate                || other.StartDate == this.EndDate                || other.EndDate == this.EndDate)                return true;            if(this.StartDate > other.StartDate)            {                // Negative                if (this.EndDate.HasValue)                {                    if (this.EndDate.Value < other.StartDate)                        return true;                    if (other.EndDate.HasValue && this.EndDate.Value < other.EndDate.Value)                        return true;                }                // Negative                if (other.EndDate.HasValue)                {                    if (other.EndDate.Value > this.StartDate)                        return true;                    if (this.EndDate.HasValue && other.EndDate.Value > this.EndDate.Value)                        return true;                }                else                    return true;            }            else if(this.StartDate < other.StartDate)            {                // Negative                if (this.EndDate.HasValue)                {                    if (this.EndDate.Value > other.StartDate)                        return true;                    if (other.EndDate.HasValue && this.EndDate.Value > other.EndDate.Value)                        return true;                }                else                    return true;                // Negative                if (other.EndDate.HasValue)                {                    if (other.EndDate.Value < this.StartDate)                        return true;                    if (this.EndDate.HasValue && other.EndDate.Value < this.EndDate.Value)                        return true;                }            }            return false;        }    }
解决方法
public bool Overlaps(TimePeriod other){    return (other.StartDate >= StartDate &&                (EndDate == null || other.StartDate <= EndDate.Value)) ||           (StartDate >= other.StartDate &&               (other.EndDate == null || StartDate <= other.EndDate.Value))}
总结

以上是内存溢出为你收集整理的c# – 任何人都可以简化这个算法吗?全部内容,希望文章能够帮你解决c# – 任何人都可以简化这个算法吗?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1261150.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-08
下一篇2022-06-08

发表评论

登录后才能评论

评论列表(0条)

    保存