使用null-coalescing与属性或调用方法

时间:2011-04-04 16:08:00

标签: c# operators

可以在以下情况下使用??操作:

string str = collection["NoRepeate"] ?? null; // Will not compile 
                          //because collection["NoRepeate"] is object

这里的问题是,当{null}值为空时,无法将collection["NoRepeate"] object分配给str,而collection["NoRepeate"].ToString()会抛出异常。

我正在使用条件运算符?:

str = collection["NoRepeate"].HasValue ? collection["NoRepeate"].ToString() : null

但问题在于重复常量字符串。

5 个答案:

答案 0 :(得分:3)

我同意你的意见,这不能在单一声明中完成。空合并运算符在这里没有帮助。

我所知道的最短时间需要两个陈述。

object obj = collection["NoRepeate"];
string str = obj == null ? null : obj.ToString();

答案 1 :(得分:1)

我的解决方案是:

var field = "NoRepeate";

var str = collection[field].HasValue ? collection[field].ToString() : null;

当然,如果您没有primitive obsessions,可以在集合类中添加一个方法来执行此操作。否则你可能不得不坚持使用扩展方法。

答案 2 :(得分:1)

从集合返回的对象实际上是Nullable<object>吗?否则,您可能希望显式检查null:

var item = collection["NoRepeate"];
string str = (item == null) ? null : item.ToString();

答案 3 :(得分:1)

您可以执行以下操作:

string str = (string) collection["NoRepeate"] ?? null;

这假设对象实际上是一个字符串。如果不是,那么您将遇到运行时错误。其他解决方案更加强大。

尽管如此,让这个尽可能短暂并没有真正的意义。你应该让你的代码可读,而不是“我能写多久这个?”

答案 4 :(得分:0)

是的,如果返回的值为null,则非常可能。如果返回值为“”则为no。我一直使用它来为空值分配默认值。