[英]Nullable datetime value
Can a DateTime
value be NULL
? DateTime
值可以为NULL
吗?
I have this code: 我有这个代码:
From here I inherit my variable 从这里我继承了我的变量
namespace Transakcija
{
public class Line
{
public System.DateTime DateOfProduction { get; set; }
}
}
Then for each loop: 然后为每个循环:
foreach (var rw_det in dt_stavke.Rows)
{
var list = new List<Transakcija.Line>();
var l = new Transakcija.Line();
//DateOfProduction
if (rw_det["DPRO02"].ToString().Length <= 0)
{
l.DateOfProduction = default(DateTime);
}
else
{
l.DateOfProduction = new DateTime();
prod_date = rw_det["DPRO02"].ToString();
DateTime pro_date = DateTime.ParseExact(prod_date, "dd.MM.yyyy", CultureInfo.InvariantCulture);
string p_date = pro_date.ToString("yyyy-MM-dd");
l.DateOfProduction = DateTime.Parse(p_date);
}
}
So the value l.DateOfProduction
needs to be null. 所以
l.DateOfProduction
的值必须为null。 I have tried this: 我试过这个:
DateTime? dt = null;
l.DateOfProduction = (DateTime)dt;
But I got error: nullable object must have a value
但我得到错误:
nullable object must have a value
So is this possible or do I have to pass the minimum datetime
value to the variable? 这是可能的,还是我必须将最小
datetime
值传递给变量?
DateTime
is a value type, so no it can never be null
. DateTime
是一个值类型,因此不能永远不为null
。 If you need a "no value" value, use a Nullable<DateTime>
or for short DateTime?
如果您需要“无值”值,请使用
Nullable<DateTime>
或简短的DateTime?
You can assigne a nullable DateTime
by using the constructor : 您可以使用构造函数来设置可为空的
DateTime
:
DateTime? dt = new Nullable<DateTime>();
You can check if a nullable type is null
by using the HasValue
property: 您可以使用
HasValue
属性检查可空类型是否为null
:
if(dt.HasValue)
{
// now you can safely use dt.Value as DateTime,
// otherwise accessing the Value property raises an InvalidOperationException
DateTime otherDate = dt.Value;
}
yoe can have Dateime Nullable this way yoe可以通过这种方式拥有Dateime Nullable
DateTime? dtNullable = new Nullable<DateTime>();
if(dtNullable.HasValue)
l.DateOfProduction = dtNullable.Value;
PS: example if you passing a non nullable DateTime to a Nullable DateTime then it will require casting PS:例如,如果您将不可为空的DateTime传递给Nullable DateTime,那么它将需要强制转换
Like this 像这样
DateTime? nullableDateTime = (DateTime?)nonNullableDateTime;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.