C# 在 ToString() 之前检查 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/550374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking for null before ToString()
提问by Dscoduc
Here's the scenario...
这是场景...
if (entry.Properties["something"].Value != null)
attribs.something = entry.Properties["something"].Value.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?
虽然有效且工作正常,但对我来说这看起来很难看。如果我在执行 ToString() 之前没有检查空值,那么如果该属性为空值,它就会抛出异常。有没有更好的方法来处理这种情况?
Much appreciated!
非常感激!
采纳答案by Rex M
Update 8 years later (wow!) to cover c# 6's null-conditional operator:
8 年后更新(哇!)以涵盖c# 6 的空条件运算符:
var value = maybeNull?.ToString() ?? String.Empty;
Other approaches:
其他方法:
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();
}
回答by PhilChuang
As a variation to RexM's answer:
作为 RexM 答案的变体:
attribs.something = (entry.Properties["something"].Value ?? attribs.something).ToString()
The only downside would be that the attribs.something would be assigned a value (itself, in this example) even if entry.Properties["something"].Value was null - which could be expensive if the .something property did some other processing and/or this line executes a lot (like in a loop).
唯一的缺点是,即使 entry.Properties["something"].Value 为 null,也会为 attribs.something 分配一个值(在本例中是它本身)——如果 .something 属性进行了一些其他处理,这可能会很昂贵和/或这条线执行了很多(就像在循环中)。
回答by Zach Scrivena
How about using an auxiliary method like this:
如何使用这样的辅助方法:
attribs.something = getString(
entry.Properties["something"].Value,
attribs.something);
static String getString(
Object obj,
String defaultString)
{
if (obj == null) return defaultString;
return obj.ToString();
}
Alternatively, you could use the ??
operator:
或者,您可以使用??
运算符:
attribs.something =
(entry.Properties["something"].Value ?? attribs.something).ToString();
(note the redundant ToString()
call when the value is null
)
(注意ToString()
值为 时的冗余调用null
)
回答by Mike Hall
To do precisely what you're trying to do a helper method can always be used:
要准确地执行您要执行的操作,始终可以使用辅助方法:
CopyIfNotNull(entry.Properties["something"].Value, out attribs.something);
void CopyIfNotNull(string src, out string dest)
{
if(src != null)
dest = src;
}
回答by Dale Ragan
If you are targeting the .NET Framework 3.5, the most elegant solution would be an extension method in my opinion.
如果您的目标是 .NET Framework 3.5,我认为最优雅的解决方案是扩展方法。
public static class ObjectExtensions
{
public static string NullSafeToString(this object obj)
{
return obj != null ? obj.ToString() : String.Empty;
}
}
Then to use:
然后使用:
attribs.something = entry.Properties["something"].Value.NullSafeToString();
回答by NotDan
Can you not do:
你不能这样做:
attribs.something = entry.Properties["something"].Value as string;
回答by aljj
attribs.something = string.Format("{0}",entry.Properties["something"].Value)
回答by Vahid
Convert.ToString(entry.Properties["something"].Value);
回答by Dave the Rave
Is it somehow possible to do something like Dale Ragan's answer above, but overriding ToString() instead of creating a new NullSafeToString() method? I'd like this (or returning "null") to be the default behaviour. The compiler (Visual C# 2010 Express) doesn't complain when I add the following method to public static class ObjectExtensions, but the method doesn't get called...
是否有可能以某种方式执行 上述 Dale Ragan 的回答,但覆盖 ToString() 而不是创建新的 NullSafeToString() 方法?我希望这个(或返回“null”)成为默认行为。当我将以下方法添加到公共静态类 ObjectExtensions 时,编译器 (Visual C# 2010 Express) 不会抱怨,但该方法没有被调用......
public static String ToString(this Object obj)
{
if (obj == null)
{
return "null";
}
else
{
return obj.GetType().Name;
}
}
回答by Dave the Rave
attribs.something = String.Format("{0}", entry.Properties["something"].Value);
Not sure about performance though...
虽然不确定性能...