可以为空的DateTime转换

ONY*_*NYX 26 c# sql asp.net entity-framework

可能重复:
c#为什么不能将可为空的int赋值为null

我试图将我的阅读器[3]对象的日期时间转换为null,如果论坛没有lastPostDate,但它说我错过了转换.错误:

无法确定条件表达式的类型,因为<null>'System.DateTime' 之间没有隐式转换

public class Forums
{
    public List<Forum> GetForums()
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CMS"].ConnectionString))
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand("sproc_Forums_GetForums", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default);

            List<Forum> forums = new List<Forum>();
            while (reader.Read())
            {
                var title = reader[6].ToString();
                var threadCount = (int)reader[5];
                var lastPostTitle = reader[4].ToString();
                // below is where im having a problem
                Nullable<DateTime> lastPostDate = (reader[3] == DBNull.Value ? null : Convert.ToDateTime(reader[3])); 
                var lastPostBy = reader[2].ToString();
                var forumGroup = reader[1].ToString();
                var description = reader[0].ToString();

                Forum forum = new Forum(0, "",DateTime.Now,
                    reader["Title"].ToString(),description,
                    0,false,"","",DateTime.Now,true,
                    forumGroup, (int)threadCount, lastPostBy,
                    lastPostDate, lastPostTitle);
                forums.Add(forum);/**/

            }
            return forums;

        }

    }            
}
Run Code Online (Sandbox Code Playgroud)

下面是我的具有Nullable lastPostDate的论坛的类对象

    public class Forum
{
    public Forum(int forumID, string addedBy, DateTime addedDate, string title, string description, int parentID, bool moderated,
        string imageUrl, string updatedBy, DateTime? updatedDate, bool active, string forumGroup, int threadCount, string lastPostBy,
        Nullable<DateTime> lastPostDate, string lastPostTitle)
    {
        this.ForumID = forumID;
        this.AddedBy = addedBy;
        this.AddedDate = addedDate;
        this.Title = title;
        this.Description = description;
        this.ParentID = parentID;
        this.Moderated = moderated;
        this.ImageUrl = imageUrl;
        this.UpdatedBy = updatedBy;
        this.UpdatedDate = updatedDate;
        this.Active = active;
        this.ForumGroup = forumGroup;
        this.ThreadCount = threadCount;
        this.LastPostBy = lastPostBy;
        this.LastPostDate = lastPostDate;
        this.LastPostTitle = lastPostTitle;
    }

    private int _forumID;
    public int ForumID
    {
        get { return _forumID; }
        set { _forumID = value; }
    }
    private string _addedBy;
    public string AddedBy
    {
        get { return _addedBy; }
        set { _addedBy = value; }
    }
    private DateTime _addedDate = DateTime.Now;
    public DateTime AddedDate
    {
        get { return _addedDate; }
        set { _addedDate = value; }
    }
    private string _title = "";
    public string Title
    {
        get { return _title; }
        set { _title = value; }
    }
    private string _description = "";
    public string Description
    {
        get { return _description; }
        set { _description = value; }
    }
    private int _parentID = 0;
    public int ParentID
    {
        get { return _parentID; }
        set { _parentID = value; }
    }
    private bool _moderated = false;
    public bool Moderated
    {
        get { return _moderated; }
        set { _moderated = value; }
    }
    private string _imageUrl = "";
    public string ImageUrl
    {
        get { return _imageUrl; }
        set { _imageUrl = value; }
    }
    private string _updatedBy = "";
    public string UpdatedBy
    {
        get { return _updatedBy; }
        set { _updatedBy = value; }
    }
    private DateTime? _updatedDate = null;
    public DateTime? UpdatedDate
    {
        get { return _updatedDate; }
        set { _updatedDate = value; }
    }
    private bool _active = false;
    public bool Active
    {
        get { return _active; }
        set { _active = value; }
    }
    private string _forumGroup = "";
    public string ForumGroup
    {
        get { return _forumGroup; }
        set { _forumGroup = value; }
    }
    private int _threadCount = 0;
    public int ThreadCount
    {
        get { return _threadCount; }
        set { _threadCount = value; }
    }
    private string _lastPostBy = "";
    public string LastPostBy
    {
        get { return _lastPostBy; }
        set { _lastPostBy = value; }
    }
    private Nullable<DateTime> _lastPosteDate = null;
    public Nullable<DateTime> LastPostDate
    {
        get { return _lastPosteDate; }
        set { _lastPosteDate = value; }
    }
    private string _lastPostTitle = "";
    public string LastPostTitle
    {
        get { return _lastPostTitle; }
        set { _lastPostTitle = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

gdo*_*ica 28

确保这两种类型 nullable DateTime

var lastPostDate = reader[3] == DBNull.Value ?
                                        null : 
                                   (DateTime?) Convert.ToDateTime(reader[3]);
Run Code Online (Sandbox Code Playgroud)
  • 使用DateTime?而不是Nullable<DateTime>节省时间......
  • 使用更好的缩进?像我一样表达.

我在Eric Lippert 博客中找到了这个出色的解释:

?:操作员的规范说明如下:

?:运算符的第二个和第三个操作数控制条件表达式的类型.设X和Y是第二个和第三个操作数的类型.然后,

  • 如果X和Y是相同的类型,那么这是条件表达式的类型.

  • 否则,如果从X到Y存在隐式转换,但不存在从Y到X的隐式转换,则Y是条件表达式的类型.

  • 否则,如果存在从Y到X的隐式转换,但不存在从X到Y的隐式转换,则X是条件表达式的类型.

  • 否则,无法确定表达式类型,并发生编译时错误.

编译器不会检查可以"保存"这两种类型的类型.

在这种情况下:

  • null并且DateTime不是同一类型.
  • null 没有隐式转换 DateTime
  • DateTime 没有隐式转换 null

所以我们最终得到了一个编译时错误.


jmo*_*eno 28

你可能想这样做:

DateTime? lastPostDate =  (DateTime?)(reader.IsDbNull(3) ? null : reader[3]); 
Run Code Online (Sandbox Code Playgroud)

你遇到的问题是三元运算符想要在左右两侧之间进行可行的演员表演.并且null不能转换为DateTime.

注意上面的工作是因为三元的两边都是对象.该对象显式转换为DateTime?哪个有效:只要读者[3]实际上是约会.


pho*_*oog 8

转换null文字:(DateTime?)null(Nullable<DateTime>)null.

你也可以使用default(DateTime?)default(Nullable<DateTime>)

并且,正如其他答案所指出的,您还可以将强制转换应用于DateTime值而不是null文本.

编辑(改编自我对Prutswonder的回答):

关键是条件运算符不考虑其赋值目标的类型,因此只有在从第二个操作数的类型到第三个操作数的类型或从第三个操作数的类型进行隐式转换时才会进行编译.操作数到其第二个操作数的类型.

例如,这将无法编译:

bool b = GetSomeBooleanValue();
object o = b ? "Forty-two" : 42;
Run Code Online (Sandbox Code Playgroud)

object但是,转换第二个或第三个操作数可以解决问题,因为存在从int到对象以及从字符串到对象的隐式转换:

object o = b ? "Forty-two" : (object)42;
Run Code Online (Sandbox Code Playgroud)

要么

object o = b ? (object)"Forty-two" : 42;
Run Code Online (Sandbox Code Playgroud)


Ama*_*ure 5

你可以试试这个

var lastPostDate = reader[3] == DBNull.Value ?
                                default(DateTime?): 
                                Convert.ToDateTime(reader[3]);
Run Code Online (Sandbox Code Playgroud)