C#可为空<;日期时间>;串
我有一个C#可为空<;日期时间>;串,c#,datetime,C#,Datetime,我有一个DateTime?变量,有时值是null,当值是null时如何返回空字符串”,或者当值不是null时如何返回DateTime值?您可以编写一个扩展方法 DateTime? MyNullableDT; .... if (MyNullableDT.HasValue) { return MyNullableDT.Value.ToString(); } return ""; public static string ToStringSafe(this DateTime? t) {
DateTime?
变量,有时值是null
,当值是null
时如何返回空字符串”
,或者当值不是null
时如何返回DateTime
值?您可以编写一个扩展方法
DateTime? MyNullableDT;
....
if (MyNullableDT.HasValue)
{
return MyNullableDT.Value.ToString();
}
return "";
public static string ToStringSafe(this DateTime? t) {
return t.HasValue ? t.Value.ToString() : String.Empty;
}
...
var str = myVariable.ToStringSafe();
实际上,这是可空类型的默认行为,即如果没有值,它们将不返回任何内容:
public class Test {
public static void Main() {
System.DateTime? dt = null;
System.Console.WriteLine("<{0}>", dt.ToString());
dt = System.DateTime.Now;
System.Console.WriteLine("<{0}>", dt.ToString());
}
}
公共类测试{
公共静态void Main(){
System.DateTime?dt=null;
System.Console.WriteLine(“,dt.ToString());
dt=System.DateTime.Now;
System.Console.WriteLine(“,dt.ToString());
}
}
这就产生了
<>
<2009-09-18 19:16:09>
尽管这些答案中有许多是正确的,但它们都是不必要的复杂如果值在逻辑上为null,则对可为null的DateTime调用ToString的结果已经是空字符串。只需对值调用ToString;它将完全执行您想要的操作。在可为null的上调用.ToString()
即null
将返回一个空字符串。您只需调用.ToString()
。它处理null
值的null
对象
以下是Nullable.ToString()
的示例:
根据:
如果HasValue属性为true,则为当前可空对象值的文本表示形式;如果HasValue属性为false,则为空字符串(“”)
谢谢你,正是我想要的什么!?只需在可为null的实例上调用.ToString()即可获得String.Empty。甚至Eric Lippert(可能已经实现了这种行为)也注意到了这一点。这应该是公认的答案。@codekaizen-当我尝试这样做时,我得到了一个例外。所以不,这不是公认的答案。在c#或.net?@k.robinson的较新版本中,这可能不是一个问题-可能是因为您使用了对实例的装箱引用。请注意,我所提倡的和Eric Lippert一样,Eric Lippert是.Net平台本身的创建者之一,他在回答中指出。如果您有问题,您可能需要重新考虑“选择未被破坏”()。@codekaizen-Ok。我仍然希望我能在没有类型转换的情况下完成这项工作:dateTimeField.Text=dateTimeObj.HasValue?((DateTime)dateTimeObj.toSortDateString():string.Empty+我不知道这件事。但是,您不能以这种方式提供格式字符串。嗯,对。虽然在这种情况下这可能不是问题。不过,直到昨天我自己才知道这一点。在Reflector:-)中查看null
时绊倒了它,或者更好:使它成为通用的:公共静态字符串ToSafeString(这个T?obj),其中T:struct
:)Holy smokes,没有意识到.NET有这个能力!除非您想使用DateTime属性,如.Day
.Week
,因为这样会得到整个DateTime字符串,并失去DateTime类的功能。e、 g.myVariable.Value.Hour.ToString()
。这只是一个例子,说明了为什么您可能希望这样做。@baron,这些属性不可为null
。这已经由
DateTime d?;
string s = d.HasValue ? d.ToString() : string.Empty;
public static string ToStringSafe(this DateTime? t) {
return t.HasValue ? t.Value.ToString() : String.Empty;
}
...
var str = myVariable.ToStringSafe();
public class Test {
public static void Main() {
System.DateTime? dt = null;
System.Console.WriteLine("<{0}>", dt.ToString());
dt = System.DateTime.Now;
System.Console.WriteLine("<{0}>", dt.ToString());
}
}
<>
<2009-09-18 19:16:09>
public override string ToString() {
return hasValue ? value.ToString() : "";
}