Ber*_* IT 47 c# datetime attributes const
我想在属性参数中放置一个恒定的日期时间,如何创建一个恒定的日期时间?它与ValidationAttributeEntLib验证应用程序块的一个相关,但也适用于其他属性.
当我这样做:
private DateTime _lowerbound = new DateTime(2011, 1, 1);
[DateTimeRangeValidator(_lowerbound)]
Run Code Online (Sandbox Code Playgroud)
我去拿:
An object reference is required for the non-static field, method, or property _lowerbound
Run Code Online (Sandbox Code Playgroud)
通过这样做
private const DateTime _lowerbound = new DateTime(2011, 1, 1);
[DateTimeRangeValidator(_lowerbound)]
Run Code Online (Sandbox Code Playgroud)
我去拿:
类型'System.DateTime'不能声明为const
有任何想法吗?走这条路不是首选:
[DateTimeRangeValidator("01-01-2011")]
Run Code Online (Sandbox Code Playgroud)
Jon*_*han 34
正如之前的一些响应所指出的那样const DateTime,C#本身不支持a,不能用作属性参数.尽管如此,a readonly DateTime(const在Effective C#,第2版[第2项]中推荐使用)是其他情况的简单解决方法,如下所示:
public class MyClass
{
public static readonly DateTime DefaultDate = new DateTime(1900,1,1);
}
Run Code Online (Sandbox Code Playgroud)
Jer*_*ose 24
我一直读到的解决方案是要么转到字符串的路径,要么将日/月/年作为三个单独的参数传递,因为C#当前不支持DateTime文字值.
这是一个简单的例子,它允许您传入三个类型的参数int,或者string传入属性:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
DateTimeRangeValidator 可以采用字符串表示(ISO8601 格式)作为参数
例如
LowerBound UpperBound
[DateTimeRangeValidator("2010-01-01T00:00:00", "2010-01-20T00:00:00")]
Run Code Online (Sandbox Code Playgroud)
单个参数将被解释为UpperBound,因此如果您想输入 LowerBound,则需要 2。检查文档以查看UpperBound是否有一个特殊的“不关心”值,或者您是否需要将其设置为一个很远的未来日期。
哎呀,只是重新阅读并注意到
'走这条路是不可取的'
[DateTimeRangeValidator("01-01-2011")]
Run Code Online (Sandbox Code Playgroud)
为什么不?
将
private const string LowerBound = "2010-01-01T00:00:00";
private const string UpperBound = "2010-01-20T00:00:00";
[DateTimeRangeValidator(LowerBound, UpperBound)]
Run Code Online (Sandbox Code Playgroud)
比(VB 日期文字格式)更差/不同
private const DateTime LowerBound = #01/01/2000 00:00 AM#;
private const DateTime UpperBound = #20/01/2000 11:59 PM#;
[DateTimeRangeValidator(LowerBound, UpperBound)]
Run Code Online (Sandbox Code Playgroud)
嗯,
艾伦
| 归档时间: |
|
| 查看次数: |
51681 次 |
| 最近记录: |