C# 仅当值大于/小于当前值时,才能指定值吗?
我想知道是否有一个操作符可以简化这个过程? 类似于+=运算符C# 仅当值大于/小于当前值时,才能指定值吗?,c#,operators,C#,Operators,我想知道是否有一个操作符可以简化这个过程? 类似于+=运算符 if (x > val) x = val; x "new operator" val; //date times DateTime d1 = dsi_curr.cycleSteps.StepsUpTimestamp[0] ; DateTime d2 = dsi_curr.cycleSteps.StepsUpTimestamp[dsi_curr.cycleSteps.StepsUpTimestamp.Length-1]; i
if (x > val) x = val;
x "new operator" val;
//date times
DateTime d1 = dsi_curr.cycleSteps.StepsUpTimestamp[0] ;
DateTime d2 = dsi_curr.cycleSteps.StepsUpTimestamp[dsi_curr.cycleSteps.StepsUpTimestamp.Length-1];
if (d1 < curbt.details.StartDate) {
curbt.details.StartDate = d1;
}
if (d2 > curbt.details.EndDate) {
curbt.details.EndDate = d2;
}
如果(x>val)x=val;
x“新操作员”val;
//日期时间
DateTime d1=dsi_curr.cycleSteps.StepsUpTimestamp[0];
DateTime d2=dsi_curr.cycleSteps.StepsUpTimestamp[dsi_curr.cycleSteps.StepsUpTimestamp.Length-1];
如果(d1<路缘细节开始日期){
curbt.details.StartDate=d1;
}
如果(d2>路缘细节.结束日期){
curbt.details.EndDate=d2;
}
对于简单类型,可以使用Math.Min()
和Math.Max()
,但不能使用DateTime
它仍将进行赋值,但会重新赋值。此操作没有内置运算符,但您可以添加自己的方法来简化此操作:
static void MakeLesserOf(ref DateTime self, DateTime other) {
self = self > other ? other : self;
}
static void MakeGreaterOf(ref DateTime self, DateTime other) {
self = self < other ? other : self;
}
如果您想了解如何简化条件表达式,可以使用注释中提到的
curbt.details.StartDate = (d1 < curbt.details.StartDate) ? d1 : curbt.details.StartDate;
curbt.details.EndDate = (d2 > curbt.details.EndDate) ? d2 : curbt.details.EndDate;
如果我误解了你的问题,请告诉我。如果你不想写“如果”字,可以使用三元运算符:
x=x>val?val:x代码>为DateTime编写一个Min
/Max
等价物很容易。如果您的条件是false@bit2know是的,会的,但对于所有实际目的来说,这都无关紧要。当您创建一个专用方法来执行此操作时,这可能不是一个问题,但在我看来,当我看到代码执行了不必要的操作,却没有增加代码的可读性时,我怀疑这是否是程序员想要做的事情。我认为这是最好的方法,无论是使用这样的方法,还是使用扩展方法,或者使用属性。@Rhett我也想到了扩展方法。不幸的是,C#不允许您编写通过引用获取其第一个参数的扩展方法,这迫使您执行赋值:curbt.details.StartDate=curbt.details.StartDate.LesserOf(d1)
我不想写两次curbt.details.StartDate
,所以我使用了常规的静态方法。
curbt.details.StartDate = (d1 < curbt.details.StartDate) ? d1 : curbt.details.StartDate;
curbt.details.EndDate = (d2 > curbt.details.EndDate) ? d2 : curbt.details.EndDate;
if (d1 < curbt.details.StartDate) curbt.details.StartDate = d1;
if (d2 > curbt.details.EndDate) curbt.details.EndDate = d2;