在 ToString() 之前检查 null [英] Checking for null before ToString()

查看:31
本文介绍了在 ToString() 之前检查 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是场景...

if (entry.Properties["something"].Value != null)
  attribs.something = entry.Properties["something"].Value.ToString();

虽然有效且工作正常,但对我来说这看起来很难看.如果我在执行 ToString() 之前没有检查空值,那么如果该属性为空值,它就会抛出异常.有没有更好的方法来处理这种情况?

While effective and working correctly, this looks ugly to me. If I don't check for a null before performing the ToString() then it throws an exception if the property was null. Is there a better way to handle this scenario?

非常感谢!

推荐答案

8 年后更新(哇!)以涵盖 c#6 的空条件运算符:

Update 8 years later (wow!) to cover c# 6's null-conditional operator:

var value = maybeNull?.ToString() ?? String.Empty;

其他方法:

object defaultValue = "default";
attribs.something = (entry.Properties["something"].Value ?? defaultValue).ToString()

我也用过这个,虽然不是很聪明但很方便:

I've also used this, which isn't terribly clever but convenient:

public static string ToSafeString(this object obj)
{
    return (obj ?? string.Empty).ToString();
}

这篇关于在 ToString() 之前检查 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆