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?"到“系统.日期时间".存在显式转换


- 带问号的 nvarchar 列结果 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 使用 rss + c# 2022-01-01