简体   繁体   English

检查函数结果是否为空值

[英]Checking a function result for null values

In his answer to this question , BlackBear suggested replacing 在回答这个问题时 ,BlackBear建议更换

 string y = Session["key"] == null ? "none" : Session["key"].ToString();

with

 string y = (Session["key"] ?? "none").ToString();

This works great if Session["key"] is a string value, but what if I want to do this with an object? 如果Session["key"]是一个字符串值,那么这很好用,但是如果我想使用一个对象怎么办? For example, I could do this: 例如,我可以这样做:

 string y = GetMyObject() == null ? "none" : GetMyObject().ToString();

But what if I don't want to evaluate GetMyObject() twice? 但是,如果我不想两次评估GetMyObject()怎么办? Is my only choice to store the results in a variable, then check that variable for null? 我唯一的选择是将结果存储在变量中,然后检查该变量是否为null?

 var x = GetMyObject();
 string y = (x == null) ? "none" : x.ToString();

Edit: This is all theoretical - I've run into it before, but I don't have a specific example in front of me right now. 编辑:这都是理论上的-我之前已经碰到过,但是现在我面前没有具体的例子。 That being said, here's an example class. 话虽如此,这是一个示例类。

class MyObject
{
   private MyObject() { }
   public MyObject GetMyObject() { return new MyObject(); }
   public override string ToString() { return "A String"; }
}

If I do string y = (GetMyObject() ?? "none").ToString(); 如果我做string y = (GetMyObject() ?? "none").ToString(); , I get ,我得到

Operator '??' 运算符“ ??” cannot be applied to operands of type 'MyObject' and 'string'". 不能应用于'MyObject'和'string'“类型的操作数。

Ideally, I'd be able to do 理想情况下,我可以

 string y = GetMyObject().ToString() ?? "none";

and have it work even if GetMyObject() is null. 并使其即使GetMyObject()为null也能正常工作。 Basically null-coalescing operator acting as a self-contained try {} catch (NullReferenceException) {} . 基本上,空值合并运算符充当独立的try {} catch (NullReferenceException) {} I know I can't , but that would be the ideal. 我知道我做不到 ,但这将是理想的选择。

BlackBear's solution works perfectly fine as it is: BlackBear的解决方案非常完美,因为它是:

string y = (GetMyObject() ?? "none").ToString();

That will either set y to GetMyObject().ToString() (if GetMyObject() returns a non-null reference) or to "none".ToString() otherwise. 任一yGetMyObject().ToString()如果GetMyObject()返回一个非空引用)或"none".ToString()否则。 There's a tiny, tiny hit calling ToString() on a string, but I'd very much doubt that it's significant. 在字符串上调用ToString()很小,但是我非常怀疑它是否有意义。

That's fine if GetMyObject() returns object . 如果GetMyObject()返回object那就很好。 If it returns some specific type which string can't be converted to, just cast one of them to object , eg 如果它返回某个不能转换为string特定类型,则将其中之一转换为object ,例如

string y = (GetMyButton() ?? (object) "none").ToString();

Having said that, I'd probably use an extension method at that point - or just do it longhand. 话虽如此,我可能会在此时使用扩展方法-或长期使用。

It looks like you would like to use the null-safe dereferencing operator, written as ?. 看起来您想使用写为?.的空安全解引用运算符?. in some languages: 在某些语言中:

var x = GetMyObject()?.ToString() ?? "none";

Unfortunately C# doesn't have this operator. 不幸的是,C#没有此运算符。 You can do it the way you are already doing it. 您可以按照已经执行的方式进行操作。

This operator was considered for addition to the language. 考虑将此操作符添加到语言中。 However it didn't make it into any released version of C#. 但是,它没有纳入任何C#的发行版本中。

What's missing in code can [usually] be added: 通常可以添加代码中缺少的内容:

private static object SafeToString( object obj, string defaultString = "none" )
{
    return obj != null ? obj.ToString() : defaultString;
}

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

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