Constant DateTime in C#(C# 中的常量日期时间)
问题描述
我想在属性参数中放置一个恒定的日期时间,我如何制作一个恒定的日期时间?它与 EntLib 验证应用程序块的 ValidationAttribute
相关,但也适用于其他属性.
I would like to put a constant date time in an attribute parameter, how do i make a constant datetime? It's related to a ValidationAttribute
of the EntLib Validation Application Block but applies to other attributes as well.
当我这样做时:
private DateTime _lowerbound = new DateTime(2011, 1, 1);
[DateTimeRangeValidator(_lowerbound)]
我会得到:
An object reference is required for the non-static field, method, or property _lowerbound
通过这样做
private const DateTime _lowerbound = new DateTime(2011, 1, 1);
[DateTimeRangeValidator(_lowerbound)]
我会得到:
类型System.DateTime"不能声明为 const
The type 'System.DateTime' cannot be declared const
有什么想法吗?走这条路并不可取:
Any ideas? Going this way is not preferable:
[DateTimeRangeValidator("01-01-2011")]
推荐答案
我一直读到的解决方案是要么走字符串的路线,要么将日/月/年作为三个单独的参数传递,如C# 目前不支持 DateTime
文字值.
The solution I've always read about is to either go the route of a string, or pass in the day/month/year as three separate parameters, as C# does not currently support a DateTime
literal value.
这是一个简单的例子,它可以让您将三个 int
类型的参数或 string
类型的参数传递给属性:
Here is a simple example that will let you pass in either three parameters of type int
, or a string
into the attribute:
public class SomeDateTimeAttribute : Attribute
{
private DateTime _date;
public SomeDateTimeAttribute(int year, int month, int day)
{
_date = new DateTime(year, month, day);
}
public SomeDateTimeAttribute(string date)
{
_date = DateTime.Parse(date);
}
public DateTime Date
{
get { return _date; }
}
public bool IsAfterToday()
{
return this.Date > DateTime.Today;
}
}
这篇关于C# 中的常量日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 中的常量日期时间


基础教程推荐
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01