[英]best method to solve Nullable object must have a value in datetime
I have a function that get the datetime value and it converts the datetime to a string as you can see here : 我有一个获取datetime值的函数,它将datetime转换为字符串,如下所示:
public string ConvertToPersianToShow(DateTime? datetime)
{
if (datetime.HasValue)
{
PersianCalendar persian_date = new PersianCalendar();
string date;
string year = Convert.ToString(persian_date.GetYear(datetime.Value));
string Month = Convert.ToString(persian_date.GetMonth(datetime.Value));
string day = Convert.ToString(persian_date.GetDayOfMonth(datetime.Value));
date = year + "/" + Month + "/" + day;
return date;
}
else
{
return
"ثبت نشده";
}
}
as you can see here the ConvertToPersianToShow
accepts an argument and the argument can be null so 如您所见, ConvertToPersianToShow
接受一个参数,并且该参数可以为null,因此
string startdate = callenderRepository.ConvertToPersianToShow(item.StartDate.Value);
sometimes this value can be null item.StartDate.Value
so and i got this error : 有时此值可以为null item.StartDate.Value
所以我得到了这个错误:
Nullable object must have a value.
so i have to check item.StartDate.hasvalue
in the first line of my code to prevent the error. 所以我必须在代码的第一行中检查item.StartDate.hasvalue
以防止错误。
is there any best method that i can use that? 有什么最好的方法可以使用吗?
Best regards 最好的祝福
由于您的ConvertToPersianToShow
接受可为空的DateTime
并检查其是否具有值,因此您可以使用可为空的对象本身而不是其基础值来调用它:
string startdate = callenderRepository.ConvertToPersianToShow(item.StartDate);
Sometimes item.StartDate is null and you try to get its value by item.StartDate.Value . 有时item.StartDate为null,您尝试通过item.StartDate.Value获取其值。 use this: 用这个:
string startdate = callenderRepository.ConvertToPersianToShow(item.StartDate);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.