简体   繁体   English

如何在 C# 中创建可为空的字符串和日期时间值

[英]How can I make nullable string and datetime value in C#

ScdDept = fields[8] is DBNull? null:fields[8].ToString();
LeaveDate = fields[9] is DBNulL?DateTime.MaxValue:DateTime.Parse(fields[9].ToString());

I have A table and B table if I add some value to A table and I run my application same value added B table.如果我向 A 表添加一些值并运行我的应用程序相同的附加值 B 表,我有 A 表和 B 表。 But in A table LeaveDate and ScdDept is empty it looks "NULL" but B table if LeaveDate is empty it looks maksvalue and ScdDept is empty it looks empty.但是在 A 表中 LeaveDate 和 ScdDept 是空的,它看起来是“NULL”,但是 B 表如果 LeaveDate 是空的,它看起来是 maksvalue,而 ScdDept 是空的,它看起来是空的。 How can I solve this problem?我怎么解决这个问题?

Your question is not clear.你的问题不清楚。 May be maksvalue of your question is MaxValue .可能是您问题的maksvalueMaxValue

By your comment and question update I think instead of DateTime.MaxValue of LeaveDate Column you want null value.通过您的评论和问题更新,我认为您想要空值而不是LeaveDate Column 的DateTime.MaxValue

Your LeaveDate property should look like您的LeaveDate属性应如下所示

public DateTime? LeaveDate { get; set; }

and then you implement like this.然后你像这样实现。

ScdDept = fields[8] is DBNull ? null : fields[8].ToString();
LeaveDate = fields[9] is DBNull ?  (DateTime?)null : DateTime.Parse(fields[9].ToString());

Approach 1: This will set default value if data is not parsing.方法 1:如果数据未解析,这将设置默认值。 It even returns whether parsing is done or not.它甚至会返回解析是否完成。

  String.TryParse( fields[8],out ScdDept );
  DateTime.TryParse(field[9],out LeaveDate );

Approach 2: While declaring ScdDept make it as a nullable方法 2:在声明 ScdDept 时将其设为可空

private string? ScdDept ;
private DateTime? LeaveDate ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM