如何检查较高值在C#中动态的范围?
我目前需要检查程序的编写程序,我需要检查用户给出的一年是否在一定范围内。最低值是一个固定值,但是该范围的顶部应在当年限制,并在我们进入新年时自行更新。我尝试使用dateTime.now.year分配给int值进行比较,但范围无法比较非静态值。
[Range(1900, 2022, ErrorMessage = "Property built before 1900.")]
上面是所讨论的行。有建议吗?
The program im writing currently I need to check if the year given by the user is within a certain range. The bottom value is a fixed value, but the top of this range should be capped at the current year and update itself whenever we enter a new year. I have tried using DateTime.Now.Year assigned to an int value for comparison, but range can't compare non static values.
[Range(1900, 2022, ErrorMessage = "Property built before 1900.")]
Above is the line in question. Any advice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能使用属性执行此操作。属性必须使用常数值。您可以验证方法中的数据,也可以使用最小值(因为这似乎是常数。
You can't do this with an attribute. Attributes must use constant values. You could either validate the data within the method or just use a minimum value (since that seems to be a constant.
您不能将
rangeatTribute
用于此任务,因为它仅适用于最小/最大值的常数值。但是您可以为此任务制作自定义验证属性。 像这里一样
,我们隐藏了
最大
从构造函数中隐藏,并将其内部设置为当年。在其他方面,我们的新属性可作为普通rangeattribute
来工作。这里的问题在于,在创建属性实例的那一刻,
最大值
是修复的。因此,如果您在12月31日启动程序,那么在运行时24小时后,您将遇到问题,因为实际年将更改,但是您的最大
不会。不幸的是,
最大
rangeAttribute
的属性不是虚拟的,因此您不能超越它。可以使用
rangeatTribute
而不是从verialationAttribute
中求解的自定义属性来解决此问题。 Then you can reimplement the logic ofRangeAttribute
(sources availableYou can't use
RangeAttribute
for this task as it only works with constant values for min/max.But you can make custom validation attribute for this task. Something like
Here we hide the
maximum
value from constructor and internally set it to the current year. In other aspects our new attribute works as a normalRangeAttribute
.The problem here is that is
maximimum
is fixed at the moment when attribute instance is created. So, if you start a program at Dec 31, then you will have a problem after 24 hours of runtime as the real year will be changed, but yourmaximum
will not.Unfortunately, the
Maximum
property ofRangeAttribute
is not virtual so you can't override it.This problem may be solved with custom attribte not inhernited from
RangeAttribute
, but fromValidationAttribute
. Then you can reimplement the logic ofRangeAttribute
(sources available here). You can throw out the most part of reference implementation and implement all logic only forint
.