比较 C# switch 语句中的日期参数
由于某种原因,我无法比较 C# 中 Switch 语句中的两个日期参数。 同样的比较在 if
和 else if
语句中工作得很好,但在 switch
中则不然。
例子 :
switch (DateTime.Today.ToString())
{
case DateTime.Today.AddDays(-10) <= DateTime.Today;
}
For some reason i cannot compare two date parameters in the Switch statement in C#.
The same comparison works perfectly fine in if
and else if
statement but not in switch
.
Example :
switch (DateTime.Today.ToString())
{
case DateTime.Today.AddDays(-10) <= DateTime.Today;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
case
语句必须是编译时常量 (C# 规范和示例):遗憾的是,您无法使用
switch
来比较DateTime
。它更丑陋,但使用if
是这里更好的选择。A
case
statement must be a compile-time constant (C# spec and example):Unfortunately, you won't be able to use a
switch
for comparingDateTime
. It's uglier, but usingif
's is the better option here.您写错了 switch 大小写,请在此处查看更多信息 http://msdn.microsoft.com/en-us/library/06tc147t(v=VS.100).aspx
另请注意,switch case 适用于常量,因此我认为
DateTime
会不使用它,你会得到编译错误You wrote switch case wrong, check more info on it here http://msdn.microsoft.com/en-us/library/06tc147t(v=VS.100).aspx
Note also that switch cases works on constants so I think
DateTime
will not work with it, u will get compile error您可以通过将 DateTime 值转换为 long (dateTime.Ticks) 来对 DateTime 值执行 switch 语句
you can do switch statements on DateTime values by converting them to long (dateTime.Ticks)
C# 4 规范第 8.7.2 节规定,可以切换的类型必须是:
,或者可隐式转换为其中一种类型的类型(
bool
除外)。Section 8.7.2 of the C# 4 specification states that the type on which it's possible to switch has to be:
or a type that is implicitly convertible to one of those types, except to
bool
.