检查是否为空是否正确? [英] Is this correct to check if is empty?
问题描述
DateTime dateFrom;
if (dateFrom == default(DateTime))
{
msg += "Date From cannot be blank!
";
}
这是正确的吗?
推荐答案
使用可空类型。
这将允许你比较日期时间与null。
例如
Use nullable types.
This will allow you to compare date time against null.
E.g.
DateTime? dt;
if (dt == null)
{
DoSomething();
}
else
{
dt = DateTime.Now;
}
否 - 它将无法编译:您将获得使用未分配的局部变量错误。
我会将其设置为一个值,但除此之外它们是等价的:
No - it won't compile: You will get a "use of unassigned local variable" error.
I would set it to a value, but otherwise these are equivalent:
DateTime dt = DateTime.MinValue;
if (dt == default(DateTime)) Console.WriteLine("Default");
if (dt == DateTime.MinValue) Console.WriteLine("Minimum");
您将打印两条消息,但我会自己使用第二种条件形式 - 它更具可读性。
You will get both messages printed, but I would use the second condition form myself - it's a little more readable.
除了右边解决方案2中解释的想法:
这将无法编译:
In addition to the right idea explained in Solution 2:
This will not compile:
// Won't compile:
msg += "Date From cannot be blank!
";
要在字符串中使用新行,请使用'@'(详细):
To use new line inside strings, use '@' (verbose):
msg += @"Date From cannot be blank!
";
或者使用'\ n'和'\ r'的组合,但取决于目的和平台:< a href =http://en.wikipedia.org/wiki/End_of_line> http://en.wikipedia.org/wiki/End_of_line [ ^ ]。
在某些API中,这并不重要。一般情况下,请始终使用 System.Environment.NewLine
:
http://msdn.microsoft.com/en-us/library/system.environment.newline%28v=vs.110%29 .aspx [ ^ ]。
Or use combination of '\n' and '\r', but depends on purpose and on the platform: http://en.wikipedia.org/wiki/End_of_line[^].
In some API, this is not important. In general case, always use System.Environment.NewLine
:
http://msdn.microsoft.com/en-us/library/system.environment.newline%28v=vs.110%29.aspx[^].
这篇关于检查是否为空是否正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!