无法隐式转换类型“System.DateTime?"到“系统.日期时间".存在显式转换

Cannot implicitly convert type #39;System.DateTime?#39; to #39;System.DateTime#39;. An explicit conversion exists(无法隐式转换类型“System.DateTime?到“系统.日期时间.存在显式转换)
本文介绍了无法隐式转换类型“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?"到“系统.日期时间".存在显式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)