在C#中的DateTime常数 [英] Constant DateTime in C#
问题描述
我想提出一个恒定的日期和时间中的一个属性的参数,我怎么做一个恒定的日期时间?它涉及到 ValidationAttribute
的EntLib验证应用程序块,但也适用于其他属性为好。
当我这样做:
私人的DateTime _lowerbound =新日期时间(2011年,1,1);
[DateTimeRangeValidator(_lowerbound)
我会得到:
的对象引用是必需的非静态字段,方法或属性_lowerbound
和做这个
私人常量的DateTime _lowerbound =新日期时间(2011年,1,1);
[DateTimeRangeValidator(_lowerbound)
我会得到:
类型'System.DateTime的'不能声明为const
块引用>任何想法?走出这种方式是不是preferable:
[DateTimeRangeValidator(2011年1月1日)]
解决方案解决方案我一直读到是要么去一个字符串的路线,或日/月/年通过三个独立的参数, C#目前不支持
的DateTime
文本值。下面是一个简单的例子,可以让你在类型可以是3个参数传递
INT
或字符串
到属性:公共类SomeDateTimeAttribute:属性
{
私人的DateTime _date; 公共SomeDateTimeAttribute(INT年,月整型,诠释天)
{
_date =新日期时间(年,月,日);
} 公共SomeDateTimeAttribute(串号)
{
_date = DateTime.Parse(日期);
} 公众的DateTime日期
{
{返回_date; }
} 公共BOOL IsAfterToday()
{
返回this.Date> DateTime.Today;
}
}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.When I do this:
private DateTime _lowerbound = new DateTime(2011, 1, 1); [DateTimeRangeValidator(_lowerbound)]
I'll get:
An object reference is required for the non-static field, method, or property _lowerbound
And by doing this
private const DateTime _lowerbound = new DateTime(2011, 1, 1); [DateTimeRangeValidator(_lowerbound)]
I'll Get:
The type 'System.DateTime' cannot be declared const
Any ideas? Going this way is not preferable:
[DateTimeRangeValidator("01-01-2011")]
解决方案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.Here is a simple example that will let you pass in either three parameters of type
int
, or astring
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#中的DateTime常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!