Cannot implicitly convert type #39;System.DateTime?#39; to #39;System.DateTime#39;. An explicit conversion exists(无法隐式转换类型“System.DateTime?到“系统.日期时间.存在显式转换)
问题描述
我正在尝试将 DateTime?
转换为 DateTime
但我收到此错误:
I am trying to convert DateTime?
to DateTime
but I get this Error:
错误 7 无法隐式转换类型System.DateTime?"到'系统.日期时间'.存在显式转换
Error 7 Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists
这是我的代码:
public string ConvertToPersianToShow(DateTime? datetime)
{
DateTime dt;
string date;
dt = datetime;
string year = Convert.ToString(persian_date.GetYear(dt));
string month = Convert.ToString(persian_date.GetMonth(dt));
string day = Convert.ToString(persian_date.GetDayOfMonth(dt));
if (month.Length == 1)
{
month = "0" + Convert.ToString(persian_date.GetMonth(dt));
}
if (day.Length == 1)
{
day = "0" + Convert.ToString(persian_date.GetDayOfMonth(dt));
}
//date = Convert.ToString(persian_date.GetYear(dt)) + "/" +
Convert.ToString(persian_date.GetMonth(dt)) + "/" +
//Convert.ToString(persian_date.GetDayOfMonth(dt));
date = year + "/" + month + "/" + day+"("+dt.Hour+":"+dt.Minute+")";
return date;
}
推荐答案
你有 3 个选项:
1) 获取默认值
dt = datetime??DateTime.Now;
如果 datetime
为空,它将分配 DateTime.Now
(或您想要的任何其他值)
it will assign DateTime.Now
(or any other value which you want) if datetime
is null
2) 检查日期时间是否包含值,如果不包含则返回空字符串
2) Check if datetime contains value and if not return empty string
if(!datetime.HasValue) return "";
dt = datetime.Value;
3) 将方法的签名更改为
3) Change signature of method to
public string ConvertToPersianToShow(DateTime datetime)
这一切都是因为 DateTime?
意味着它可以为空 DateTime
所以在将它分配给 DateTime
之前,您需要检查它是否包含值,然后才分配.
It's all because DateTime?
means it's nullable DateTime
so before assigning it to DateTime
you need to check if it contains value and only then assign.
这篇关于无法隐式转换类型“System.DateTime?"到“系统.日期时间".存在显式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法隐式转换类型“System.DateTime?"到“系统.日期时间".存在显式转换


基础教程推荐
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01