我们希望避免出现 NullReferenceException
。目前我们有:
ISomeInterface interface = this.GetISomeInterfaceInstance();
(interface as ClassImplmentsISomeInterface).Method();
这工作正常,但存在 NullReferenceException
风险。一种解决方案是:
ISomeInterface interface = this.GetISomeInterfaceInstance();
ClassImplmentsISomeInterface instance = interface as ClassImplmentsISomeInterface;
if (instance != null)
instance.Method();
但是这会产生大量额外的代码用于简单检查(根据 resharper 有 100 种可能的 NRE。)第二种解决方法是:
ISomeInterface interface = this.GetISomeInterfaceInstance();
if (interface is ClassImplmentsISomeInterface)
(interface as ClassImplmentsISomeInterface).Method();
但我收集到 is
实际上在后台使用 as
,因此进行了两次转换,我想避免这种情况。这有关系吗?例如,C# 编译器是否足够聪明来优化这个性能问题?
我还缺少其他一些技巧吗?还是上述方法中的一种更可取?
最佳答案
我能想到一个能让你的代码更短的好方法:
public static void InvokeIfIsT<T>(object o, Action<T> action)
{
if (o is T)
action((T)o);
}
像这样使用它:
ISomeInterface interface = this.GetISomeInterfaceInstance();
InvokeIfIsT<ClassImplmentsISomeInterface>(interface, i => i.Method());
关于c# - 转换时避免 NullReferenceException 的首选做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11984043/