[英]Checking for null before ToString()
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. 如果我在执行ToString()之前没有检查null,那么如果属性为null,则抛出异常。 Is there a better way to handle this scenario? 有没有更好的方法来处理这种情况?
Much appreciated! 非常感激!
Update 8 years later (wow!) to cover c# 6's null-conditional operator : 8年后更新(哇!)以涵盖c#6的空条件运算符 :
var value = maybeNull?.ToString() ?? ""
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();
}
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();
Convert.ToString(entry.Properties["something"].Value);
Adding an empty string to an object is a common idiom that lets you do null-safe ToString
conversion, like this: 向对象添加空字符串是一种常见的习惯用法,它允许您进行空安全的ToString
转换,如下所示:
attribs.something = ""+entry.Properties["something"].Value;
When entry.Properties["something"].Value
is null
, this quietly returns an empty string
. 当entry.Properties["something"].Value
值为null
,这会悄悄地返回一个空string
。
Edit: Starting with C# 6 you can use ?.
编辑:从C#6开始,您可以使用?.
operator to avoid null
checking in an even simpler way: 运算符以更简单的方式避免null
检查:
attribs.something = entry.Properties["something"].Value?.ToString();
// ^^
attribs.something = String.Format("{0}", entry.Properties["something"].Value);
虽然不确定性能......
你不能这样做:
attribs.something = entry.Properties["something"].Value as string;
In C# 6.0 you can do it in a very elegant way: 在C#6.0中,您可以以非常优雅的方式完成:
attribs.something = entry.Properties["something"].Value?.ToString();
And here is an article about new null-conditional operator . 这是一篇关于新的零条件运算符的文章。
attribs.something = string.Format("{0}",entry.Properties["something"].Value)
Is it somehow possible to do something like Dale Ragan's answer above , but overriding ToString() instead of creating a new NullSafeToString() method? 是否有可能像上面的Dale Ragan的回答那样做,但是重写ToString()而不是创建一个新的NullSafeToString()方法? I'd like this (or returning "null") to be the default behaviour. 我想这(或返回“null”)是默认行为。 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... 当我将以下方法添加到公共静态类ObjectExtensions时,编译器(Visual C#2010 Express)不会抱怨,但该方法不会被调用...
public static String ToString(this Object obj)
{
if (obj == null)
{
return "null";
}
else
{
return obj.GetType().Name;
}
}
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). 唯一的缺点是attribs.something将被分配一个值(在本例中本身),即使entry.Properties [“something”]。值为null - 如果.something属性做了一些其他处理,这可能会很昂贵和/或这一行执行很多(如在循环中)。
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;
}
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
) (注意当值为null
时多余的ToString()
调用)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.