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?"到“系统.日期时间".存在显式转换
基础教程推荐
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 将数据集转换为列表 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 从 C# 控制相机设备 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 如果条件可以为空 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
